Android's ActionBarActivity and the Hardware Back Button

In my last post I talked about one of the roadblocks I hit when upgrading to Android's new ActionBarActivity. That was definitely a major pain, but there's one other issue I've run into so far that I wanted to call attention to as well. This one didn't cost us nearly as much time as that last one did, but it was certainly unexpected.

Our apps make use of a single activity and fragments for each separate screen within the app. After updating this activity to extend from ActionBarActivity we noticed that suddenly the hardware back button was causing the host activity to finish, even when there were multiple fragments in the backstack. Prior to this change we could rely on the hardware back button to pop fragments off the stack first, and only finish the activity if there was nothing left in the stack.

I figured this was just a documented change, but a look at Android's documentation for onBackPressed() says:

Take care of popping the fragment back stack or finishing the activity as appropriate.

This description lines up with the behavior I would have expected, but unfortunately the observed behavior is not the same.

The fix for this in the host activity is simple enough:

public override void OnBackPressed()  
{
    if (FragmentManager.BackStackEntryCount > 0)
        FragmentManager.PopBackStack();
    else 
        base.OnBackPressed();
}

All in all it's certainly not the end of the world to add this small amount of code to work around the issue here. I was just surprised by the change in behavior, and wanted to call attention to it in case it helps one of you solve the issue in your apps before they make it out to the Play store.

comments powered by Disqus
Navigation