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?
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()
}
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With