Reputation: 519
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??
Upvotes: 6
Views: 1910
Reputation: 197
In the switch statement, change
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
to
case android.R.id.home:
onBackPressed();
return true;
Upvotes: 5
Reputation: 26198
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()
Upvotes: 6