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.
- Open the AndroidManifest.xml file by double-clicking it
- Switch to the Application tab at the bottom of the editor
- Click the Add.. button in the Application Nodes section
- Make sure Activity is selected in the pop-up dialog and click OK
- A new section will now appear to the right of Application Nodes, called Attributes for Activity.
- 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.
- 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);
}
});
}
}
Passing Objects Between Two Activities
Simple primitive data types such as ints, floats, and Strings can be passed via 'extras', by calling the appropriate putExtra() method on the Intent instance you're using to switch activities. You retrieve such extras using the corresponding getExtra() methods.For more complex data, such as a custom object, or an ArrayList of custom objects, you have a few options:
- wrap the object in a class that implements the Parcelable interface, which can be stored in an extra
- wrap the object in a class that implements the Serializable interface, which can be stored in an extra
- use static data members to store objects that need to be accessed by multiple activities
- use external storage (file, database, SharedPreferences)
- use a common component, such as a custom Application or a local Service