Search code examples
androidandroid-fragmentsback-stack

Back button support in Android fragments


I'm working on an inherited Android project that makes use of fragments. The mainactivity has a side menu drawer that allows the user to tap on a list of items, each of which opens a new fragment in another file.

Right now, pressing the back button closes the app abruptly. I wish for the back button to work such that it will bring the user back to the previously viewed fragment, and when the user is at the very first viewed fragment, pressing a back button will bring an app exit confirmation box.

I understand that I should be using addToBackStack() but I'm not sure how to implement it in my code.

Here's the code originally in mainactivity when an item is selected:

FragmentManager fm = getFragmentManager();
switch (position) {
case 0:
  if (fragmentManager.findFragmentById(R.id.content_frame != null) {
    Fragment currentFragment = fragmentManager.findFragmentById(R.id.content_frame);
    fm.befineTransaction().remove(currentFragment).commit();
    fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
  }
  Item0 item1Fragment = new Item0();
  fm.beginTransaction().replace(R.id.content_frame, item0Fragment).commit();
  break;

case 1 onwards are identical, except Item0/item0Fragment references are replaced with their respective values.

I'm very new to fragments, but from what I can see, the code is first detecting if the activity has a frame for the fragment, and if so, it removes the current fragment, and completely clears the fragment back stack. It then creates a new fragment, and replaces the current fragment with the new one.

Here's my code currently after some changes, and it seems to work, except for a few problems which I'll describe after the code:

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
switch (position) {
case 0:
  Item0 item1Fragment = new Item0();
  ft.replace(R.id.content_frame, item0Fragment).addToBackStack(null).commit();
  break;

The above modified code provides correct navigation, except:

  1. When the I've gone back to the very first fragment, then a back button press removes that fragment and presents an empty fragment on screen, and the next back button press will close the app. The desired behavior would be that a back button press on the very first fragment will bring out a confirmation button to close the app.

  2. When the items on the side menu are tapped and selected, I call mItemList.setItemChecked(position). How do I call update this when the back button is tapped so that the previous selection is selected?

Does anyone know how to make this work?

Thanks.


Solution

  • Have you checked the developer.android ? Here is how they explain. http://developer.android.com/training/implementing-navigation/temporal.html#back-fragments