Adding a Second Activity to your Android App

Android apps are organised into distinct 'activities', each represented by an instance of Activity or one of its subclasses.

When you create a new Android project in Eclipse, a default Activity is created for you. For anything beyond the most simple app, a single Activity will not be enough. The user can easily switch back and forth between different activities, and they are the basic way of subdividing distinct functionality in Android.

Here I'm going to go over the process of adding a second Activity to a project. In Eclipse, the best way is to start by creating the required entry in the application's AndroidManifest.xml file.

  1. Open the AndroidManifest.xml file by double-clicking it
  2. Switch to the Application tab at the bottom of the editor
  3. Click the Add.. button in the Application Nodes section
  4. Make sure Activity is selected in the pop-up dialog and click OK
  5. A new section will now appear to the right of Application Nodes, called Attributes for Activity.
  6. Click the underlined link Name in this section and the New Java Class wizard opens, with the superclass and package prefilled. If you want to extend a class other than Activity, e.g. ListActivity, you can change that here.
  7. Enter a name for your new Activity, and also check the box to create stubs for 'Inherited abstract methods'

The Eclipse editor will then open showing the newly generated class code that you can edit at your leisure.

Switching to Your App's Second Activity

If you add a button to your app's main layout file with the ID switcherbtn, the following code is how you would set an onClick() listener to make that button switch to the other activity you created above:

public class MainActivity extends Activity {
    private Button btnSwitcher;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Get hold of your switcher button
        btnSwitcher = (Button) findViewById(R.id.switcherbtn);

        // Set an onClick listener so the button will switch to the other activity
        btnSwitcher.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Switch to Other Activity
                Intent myIntent = new Intent(v.getContext(), OtherActivity.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }
}

Obviously you'll need to change OtherActivity for the name you gave your other Activity class.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options


Theme port sponsored by Duplika Hosting reloaded by Deeson Design
Home Back To Top