Wednesday, March 13, 2013

How to Create Multiple Activities on the Android



1. Open your Android project in Eclipse, the official development environment for coding Android apps. Locate your project in the Package Explorer on the left side of the main Eclipse window. Typically, a number of directories, files and folders will be found within the application package for a single app. When Eclipse creates your project, it typically creates one default activity class, which is launched when users run your app. To view the classes in your app, open the 'src' folder in the project and then open the default package, which you named when you created the project in Eclipse. Inside this directory, you should see one or more Java files.

2. Create a new activity class in your project. Right-click the default package, choose 'New' and then select 'Class' before entering the name of the new class. Eclipse will automatically open the new class file in the editor pane; some of the code will be pre-filled. Modify the class to extend the activity class as in this example:public class LovelyScreen extends Activity {

//class implementation

}You will also need to import the activity class, so add the following line above the class declaration outline:import android.app.Activity;

3. Override the 'onCreate' method for your activity class. To define what should happen when users launch an activity screen, you can include code in the 'onCreate' method, as in the following example:public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

//class details

}This calls the method of the super-class being extended. A common processing step is to specify a layout, as in the following example:setContentView(R.layout.main);This code instructs Android to use the XML layout specified within the 'main.xml' layout file. You can create a layout file for each of your activities if you like.

4. Add your activity to the manifest file for your app. Inside the 'AndroidManifest.xml' file that you should find in the Eclipse Package Explorer for your application package, you need to add the details of each activity. Open your manifest file and add code using the following syntax:

Modify the name to suit your own class. You should see your main app class in the manifest already, but its listing is slightly different because it is launched when users start the app.

5. Create an “intent” to launch your activity. In a class outside the new activity class, from wherever you want to launch it, create the intent using the following syntax:Intent myScreen = new Intent(this, LovelyScreen.class);

this.startActivity(myScreen);This code starts the activity defined by the new class. Change the class name to suit your own application. Repeat the process of creating a new class, extending the activity class, overriding the 'onCreate' method, adding to the manifest and starting an intent for each new activity you need in your app.

No comments:

Post a Comment