Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make back icon to behave same as physical back button in Android?

Tags:

android

back

I have MainActivity and SecondActivity.

AndroidManifest.xml

<activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
    android:name=".SecondActivity"
    android:label="@string/title_activity_second_activitity"
    android:parentActivityName=".MainActivity" >
</activity>

While I hit the back icon of SecondActivity, it's more likely that MainActivity is pushed on SecondActivity. Instead, physical back button will make SecondActivity pops up and back to MainActivity.

How can I make the back arrow icon to behave the same as physical back button?

like image 763
willowcheng Avatar asked Feb 10 '15 17:02

willowcheng


2 Answers

Physical back button and icon back button aren't supposed to work in the same way according to the google's guidelines. But if you want to change it's behavior then you need to override it's functionality by doing the next:

On your SecondActivity override onOptionsItemSelected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        onBackPressed();    //Call the back button's method
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Also you need to remove android:parentActivityName=".MainActivity" from your manifest but to avoid the back icon to be removed you need to set it enabled:

@Override
public boolean onCreate(Bundle savedInstanceState) {

    ...

    ActionBar actionBar = getActionBar();  //Make sure you are extending ActionBarActivity
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    //It's also possible to use getSupportActionBar()
}
like image 87
Carlos J Avatar answered Nov 14 '22 22:11

Carlos J


Carlos' answer works. There is also another way which I think is more straight forward: just add a click listener directly to the back icon.

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        finish();
        }
    });
like image 29
Kevin Zhang Avatar answered Nov 14 '22 21:11

Kevin Zhang