Activity's Up button to navigate to different activities

123 Views Asked by At

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?

3

There are 3 best solutions below

1
Zwal Pyae Kyaw On BEST ANSWER

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!

2
Arahasya On

Replace with this:

 <activity
        android:name=".MyActivity"

        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
 </activity>
1
DB377 On

Just remove meta-data declaring parent activity if you don't want to go to home activity.

<activity android:name="com.myapp.activity.MyActivity" />

or you can use toolbar's onNavigationClick to define your own action on back press:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //if you want to go one activity back then put onBackPressed() method
        onBackPressed();
    }
});