Your app should make it easy for users to find their way back to the app’s main screen. One simple way to do this is to provide an Up button on the app bar for all activities except the main one. When the user selects the Up button, the app navigates to the parent activity.
This lesson shows you how to add an Up button to an activity by declaring the activity’s parent in the manifest, and enabling the app bar’s Up button.
Declare a Parent Activity
To support the up functionality in an activity, you need to declare the activity’s parent. You can do this in the app manifest, by setting an android:parentActivityName
attribute.
The android:parentActivityName
attribute was introduced in Android 4.1 (API level 16). To support devices with older versions of Android, define a<meta-data>
name-value pair, where the name is "android.support.PARENT_ACTIVITY"
and the value is the name of the parent activity.
For example, suppose your app has a main activity named MainActivity
and a single child activity. The following manifest code declares both activities, and specifies the parent/child relationship:
<application ... > ... <!-- The main/home activity (it has no parent activity) --> <activity android:name="com.example.myfirstapp.MainActivity" ...> ... </activity> <!-- A child of the main activity --> <activity android:name="com.example.myfirstapp.MyChildActivity" android:label="@string/title_activity_child" android:parentActivityName="com.example.myfirstapp.MainActivity" > <!-- Parent activity meta-data to support 4.0 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.myfirstapp.MainActivity" /> </activity> </application>
Enable the Up Button
To enable the Up button for an activity that has a parent activity, call the app bar’s setDisplayHomeAsUpEnabled()
method. Typically, you would do this when the activity is created. For example, the following onCreate()
method sets a Toolbar
as the app bar for MyChildActivity
, then enables that app bar’s Up button:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_child); // my_child_toolbar is defined in the layout file Toolbar myChildToolbar = (Toolbar) findViewById(R.id.my_child_toolbar); setSupportActionBar(myChildToolbar); // Get a support ActionBar corresponding to this toolbar ActionBar ab = getSupportActionBar(); // Enable the Up button ab.setDisplayHomeAsUpEnabled(true); }
You do not need to catch the up action in the activity’s onOptionsItemSelected()
method. Instead, that method should call its superclass, as shown inRespond to Actions. The superclass method responds to the Up selection by navigating to the parent activity, as specified in the app manifest.