Up Navigation for Activities

suggest change

Up navigation is done in android by adding android:parentActivityName="" in Manifest.xml to the activity tag. Basically with this tag you tell the system about the parent activity of a activity.

How is it done?

<uses-permission android:name="android.permission.INTERNET" />

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
    <activity android:name=".ui.activities.MainActivity" />
    <activity android:name=".ui.activities.HomeActivity"
     android:parentActivityName=".ui.activities.MainActivity/> // HERE I JUST TOLD THE SYSTEM THAT MainActivity is the parent of HomeActivity

Now when i will click on the arrow inside the toolbar of HomeActivity it will take me back to the parent activity.

Java Code

Here i will write the appropriate java code required for this functionality.

public class HomeActivity extends AppCompatActivity {
    Toolbar toolbar;    

    protected void onCreate(Bundle savedInstanceState) {
        //Since i am using custom tool bar i am setting refernce of that toolbar to Actionbar. If you are not using custom then you can simple leave this and move to next line
        getSupportActionBar.setDisplayHomeAsUpEnabled(true); // this will show the back arrow in the tool bar.

If you run this code you will see when you press back button it will take you back to MainActivity. For futher understanding of Up Navigation i would recommend reading docs

You can more customize this behaviour upon your needs by overriding

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this); // Here you will write your logic for handling up navigation
        return true;
    return super.onOptionsItemSelected(item);

Simple Hack

This is simple hack which is mostly used to navigate to parent activity if parent is in backstack. By calling onBackPressed() if id is equal to android.R.id.home

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                return true;
        return super.onOptionsItemSelected(item);

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents