I have many fragments in an activity. I move to some activity from one of the fragments. There are two cases. If I press hardware back button, I move back to the fragment from which current activity was called. But using action bar back button, previous activity is launched from onCreate state,like the very first fragment that I use when that activity is launched at first. Here is the code for action bar back button for second activity:
in onCreate: getActionBar().setDisplayHomeAsUpEnabled(true);
then I use:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
How do I get the same function in action bar back button as in hardware bach button: onbackpressed??
This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
You can call the method onBackPressed();
of the Activity to give you the ability to back button just like the hardware back button.
if you are in fragment call getActivity().onBackPressed()
In the switch statement, change
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
to
case android.R.id.home:
onBackPressed();
return true;
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