Nov 282012
Article Android

In this third post in our series on programming apps in Android, we are going to use the “Hello” application presented in our previous post as a starting point to create a “HelloBye” application with two windows.

In this new app we will be adding a second window named “Bye”, and will explain how to switch from the “Hello” window to the “Bye” window and vicecersa,by means of the application contextual menu. This will also give us the opportunity to explain a bit more about the structure of an Android app.

Create a window

To create a new window in our application, me must design the layout of the window, and the Activity with the associated source code. The resources used in the layout (images, texts,…) must be created as well.

Layout and resources

The layout of the new screen es defined in a file “res/layout/bye.xml”:

We can see that this file is identical to the one that defines the layout of the main window, with the exception of a reference to the string “@string/bye_world” as the content of the TextView control. This new string must be defined in the resource file “res/values/strings.xml”:

Contextual menu

The contextual menu is the menu that pops up when the “Menu” button is pressed. We will define a menu with two options in it by editing the file “res/menu/main_menu.xml”:

  • Switch screen – To switch from “Hello” to “Bye” and viceversa
  • Exit – To leave the application

The contents of the resouce file are:

“Bye” Activity

The Activity for the new screen overrides three methods:

La actividad de la nueva pantalla contiene tres métodos:

  • onCreate – Renders the layout “bye.xml”.
  • onCreateOptionsMenu – Assigns the contextual menu defined in  “main_menu.xml” to the new screen.
  • onOptionsItemSelected – This is the code that is executed when on of the options in the menu is selected.

Changes to the “Hello” activity

We are going to assign the same contextual menu “main_menu.xml” to the “Hello” activity:

We do this by adding to the “” file a onCreateOptionsMenu method with the same code used in “”.

We add also a onOptionsItemSelected method with the actions to execute when a menu option is selected, as follows:

We must also modify the onCreate method, to check if the screen has been activated because the user selected the menu option “Exit” in the “Bye” screen. In this case, we must finalize the “Hello” activity as well, to completely quit the application:


Finally, the AndroidManifest.xml file must be edited to add the new activity:

With this, we can try the application in the emulator:

When the application starts it shows the “Hello” screen.

When the “Menu” button is pressed, the menu with the options “switch” and “exit” is displayed.

When the option “switch” is selected, the “Bye” activity is started and the “Bye” screen is displayed.

The eclipse project for this sample application can be downloaded here

 Posted by at 9:35 am

 Leave a Reply