Back Navigation in Android

There are several blogs and articles about implementing back navigation in Android. Yet a beginner would need to read a lot to figure out how to do it. Let me show you how to do it in 2 mints.

It is pretty easy. Just follow the steps as below.

Add Parent Activity in AndroidManifest.xml

Add the following to your child-activity and declare the parent-activity

android:parentActivityName="<<ParentClassName>>"

For users who are using 4.0.0 or lower versions, add the following meta-data code in the child-activity

<meta-data
    android:name="android.support.PARENT_ACTIVITY"
    android:value="org.slappforge.findyourmate.HotPlacesActivity" />

An example of the child-activity would look like below,

<activity
    android:name=".ViewProfileActivity"
    android:label="@string/title_activity_view_profile"
    android:theme="@style/AppTheme.NoActionBar"
    android:parentActivityName=".PlacesActivity">

    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.example.PlacesActivity" />
</activity>

Add a toolbar to your layout XML

Add a toolbar to your layout resource XML as below,

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_collapseMode="pin"
    app:popupTheme="@style/AppTheme.PopupOverlay" />

Setting up the Activity

Go to your Activity class and in OnCreate() add the following code,

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(username);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();

// Enable the Up button
if (ab != null) {
    ab.setDisplayHomeAsUpEnabled(true);
} else {
    throw new NullPointerException("Something went wrong");
}

Make sure that you have not called finish() in your parent-activity class when starting the child-activity.

Your Back Navigation is working fine now!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s