androidandroid-activityandroid-toolbarandroid-navigationup-button

Activity's Up button to navigate to different activities


I have an activity MyActivity with the standard Up button implemented in its toolbar (left arrow on top-left of screen).

This activity is unique in that the user can navigate to it from multiple activities in my app.

I need this Up button to direct to the activity that the user came from (same behavior as Android Back button).

Instead, it always directs back to the Home activity, even if the user did not immediately come from there, because of this code in AndroidManifest.xml:

<activity
    android:name="com.myapp.activity.MyActivity"
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.myapp.activity.Home"
/>

How do I override this behavior so that MyActivity's Up button returns the user to the activity that he came from and not always the Home activity?


Solution

  • First, replace your code with this.

    <activity
            android:name=".MyActivity">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
     </activity>
    

    Second, add a few codes to your "MyActivity" class.

    1. at onCreate() method, add that line.

    getActionBar().setDisplayHomeAsUpEnable(true);
    

    2. implement onOptionItemSelected(), add a few lines.

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
                    if (id == android.R.id.home) {
                         super.onBackPressed();
                    }
            return super.onOptionsItemSelected(item);
        }
    

    Hope it works!