AndroidPicking up where we left off yesterday in our 31 Days of Android, let’s get back to our application.  We left off with an application that was only capable of handling some very simple user input.  Your application is currently comprised of only a single activity which means it’s not capable of a lot.  To be fair, there are certainly some applications that only use one activity and accomplish quite a bit.  However, most apps will use multiple activities.  Today we’re going to talk about how to accomplish that.  For today, we’re going to work off of the same application code as last time (though the package / activity names have been renamed DayFive instead of DayFour).  You can download our starter app code here.

In Eclipse, expand the src folder in Package Explorer and right click on com.dayfive -> New -> Class.  You will then be presented with the New Java Class window.  Some of the information (the Source Folder and Package) will already be taken care of leaving the Name and Superclass for us.  The Name here is relatively arbitrary.  The Superclass is not however.  If you remember our DayFourActivity, it extended from Activity.  Setting our Superclass here will ensure that our new Activity also extends from Activity.  If you’re not familiar with Eclipse, you can click the Browse button on the right, it will help lookup classes in case you don’t know their full path (i.e. if you know you want Activity but don’t know it’s andoird.app.Activity). 

New Java Class

After clicking Finish, our new Activity will be added to our source code.  Opening it will show us a very empty new class:

public class ActivityTwo extends Activity {}

Like this, your Activity won’t do you any good.  You need to override some base functionality.  Placing your cursor inside of the curly braces and hitting Ctrl+Space will bring up different methods we can either override or implement for a class.  The method you want to override first is going to be onCreate so go ahead and select that method.  Again you have some base code that doesn’t do everything you need it to do:

   1:  @Override
   2:  protected void onCreate(Bundle savedInstanceState) {
   3:      // TODO Auto-generated method stub
   4:      super.onCreate(savedInstanceState);
   5:  }

The only thing you’re going to do with your second activity today is connect it to a Layout, however, you need to create that Layout first.  To do so, expand the res folder and right click on the layout folder.  From there go to New -> Other and then select Android XML File.  The Eclipse Android tools are pretty smart and will know what type of XML file you want to create based off of the folder you’ve right clicked on so it should already have Layout selected in the Resource Type of the next window.  The default Root Element is LinearLayout so leave that as is.  Enter a name (like “second_layout”) in the File textbox and click Finish.  If you click Next instead of Finish you can enter OPTIONAL qualifiers for your layout.  So if you wanted to make a layout specific to the portrait orientation and a different one for landscape, this is where you would do so.  We’ll cover those qualifiers another day in more detail.  After finishing, you’ll be taken to the graphical layout editor.  Again, you’re not going to get very fancy here so drag a TextView on to the layout from the Palette on the left.  By default your TextView’s id will be textView1 which is fine.  Your TextView on the other layout has a different id, however, it’s not an issue for different layouts to have views with the same id.  If, however, you have two views on the same layout with the same id, you will run into issues trying to get references to those views in your code.  Now that we’ve created a second layout, let’s go back to our ActivityTwo class.  After the call to super.onCreate you need to set the contentView to your new layout.  This is done via the following line of code:

setContentView(R.layout.second_layout);

Great, you’ve created a second activity and a layout and you’ve connected that layout to our Activity, but how do you actually show that on the screen?  To do this, you use IntentsIntents are essentially messages that you can send between different parts of your application or to the Android OS itself.  You’re going to use it in a very simple way today though Intents are incredibly powerful and will come up in several posts later in the series.  To use our first intent, we must return to the DayFiveActivity and the main.xml layout.  Go to the layout and drag another button onto the bottom beneath our “Click Me” button.  This should default to be id button2.  With this done, you can go to our code file, beneath where you get a reference for button1 and set it’s onClickListener you need to do the same for button2:

   1:  Button button2 = (Button) findViewById(R.id.button2);
   2:  button2.setOnClickListener(new OnClickListener() {            
   3:      public void onClick(View v) {                            
   4:      }
   5:  });

Now here’s where you get to the Intent.  There are assorted ways to setup an Intent and make it run.  You’re going to do the simplest way here:

   1:  button2.setOnClickListener(new OnClickListener() {            
   2:      public void onClick(View v) {
   3:          startActivity(new Intent(getApplicationContext(), ActivityTwo.class));
   4:      }
   5:  });

Here you’re instantiating an Intent object on the fly using the Application Context and your new Activity.  That gets passed into startActivity which does exactly as named.  You’re nearly ready to run now.  The last thing you need to do is make a small modification to your AndroidManifest file.  The manifest file needs to know about all the activities your application is going to run so near the bottom, between the end of the first activity and the end of the application you need to add an element for your new activity:

<activity android:name=".ActivityTwo" android:label="@string/app_name"/>

Now you can run your application.  Right Click on the application in Package Explorer and go to Run As -> Android Application or hit Ctrl+F11:

android_day_five_second

So this is your DayFive layout with the new button at the bottom.  Tapping that button should cause our new Activity to fire and give you this:

Android Day Five Third

You’ve successfully created a second activity and layout and connected your first activity to it.  This basic functionality is actually pretty critical to many applications.  Furthermore, the Intent you used was very basic but incredibly powerful. 

One thing I would like to highlight is what happens when you tap the Back button on the second activity.  Due to the way you’re starting ActivityTwo, if you tap Back, you will return to our first Activity.  You could think of your Activities as a stack of cards.  When your app starts, card 1 is put down.  When you start your second activity, card 2 is put down on top of card 1.  When you hit the back button, card 2 is taken off to reveal card 1.  If you wanted to get rid of card 1 when you show card 2, or prevent the user from backing into the first activity, you could call finish immediately after starting your second activity like so:

   1:  public void onClick(View v) {
   2:      startActivity(new Intent(getApplicationContext(), ActivityTwo.class));
   3:      finish();
   4:  }
This will end your first activity and start your second activity.  That’s all for today.  You can download the latest source code here.

Chris Risner


Leave a Comment