How to implement Up Navigation

In this example you can see how to implement the Up Navigation, i.e. the option to go back to a previous activity using the button in the upper left of the action bar.
The previous activity can be a fixed activity or an activity determined at runtime.

The following steps are the most important files, but you can download the full example here.

  1. the class MainActivity.java

    this activity is the main one, it implements the layout defined in /res/layout/main_activity.xml which consists of two buttons that launch two other activities where there is the Up Navigation button;
  2. the layout for MainActivity.java
  3. the class ChildOneActivity.java

    this class implements Up Navigation at the line 16, and the activity that is launched by pressing the “Up Navigation” button is defined in AndroidManifest.xml
  4. the layout for ChildOneActivity.java
  5. the file AndroidManifest.xml

    at the lines 19-30 I set the parent activity for the two activities “Child”
  6. the file ChildTwo.java

    as in ChildOneActivity.java also here there is the line 40 to enable the Up Navigation, but in this case the user can choose whether to launch the main activity defined in AndroidManifest.xml or to launch the activity ChildOne using the two radio buttons

    • lines 18-25: in the field parentActivityId I save the user’s choice
    • lines 46-53: if the user presses the button “Up Navigation” (line 47: case android.R.id.home) and if the user has selected “Child One” it launches the activity ChildOneActivity else it launches the activity set in AndroidManifest.xml
  7. the layout for ChildTwoActivity.java

The three activities of this example:

  • MainActivity.java
    main_activity
  • ChildOneActivity.java
    childone_activity
  • ChildTwoActivity.java
    childtwo_activity

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.