1

I have 4 fragment in my android app : let's say A B C D where they 4 are fragments called in 1 activity. When I go from A to B and from be to C I want the back button to bring me to B and to A if I press again. But instead the back button forwards me to the previous activity.

I've read that the back button need to explicitely be handled as for fragments and I saw that code :

FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();

fragment.getView().setFocusableInTouchMode(true);

fragment.getView().setOnKeyListener( new OnKeyListener()
{
@Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
    if( keyCode == KeyEvent.KEYCODE_BACK )
    {
        return true;
    }
    return false;
    }
} );

The problem is that I'm not using any FragmentTransaction. Here is how I call my Fragments :

private void displayView(int position) {
    Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;
    /*case 1:
        fragment = new ContactsFragment();
        break;*/
    case 2:
        fragment = new ContactsFragment();
        break;
    case 3:
        fragment = new SitesFragment();
        break;
    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();
}

How can I use that back stacking with my code please ? Thank you for your help in advance !

Kevin Gilles
  • 463
  • 1
  • 8
  • 23

2 Answers2

2

You need to use the FragmentTransaction to add/replace the new fragment, add it to the back stack, then commit. You do not need to handle the BACK button yourself unless you wish to override the default behavior. Adding it to the back stack in the FragmentTrasnaction before you commit will automatically pick up the desired BACK button support.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
2

By calling .beginTransaction(), you are actually using a FragmentTransaction. The type itself is just not explicitly mentioned in your example. You can simply call addToBackStack() on the transaction to add the transaction to the fragment manager's back stack:

fragmentManager.beginTransaction()
            .replace(R.id.frame_container, fragment).addToBackStack(null).commit();

Edit: As Larry pointed out, adding to the fragment manager's back stack will automatically handle going back if your structure is as simple as A>B>C>D. If, for any reason, you need to manually handle the behavior of popping the backstack, you can use these instructions below:

In your activity, override onBackPressed() and call getFragmentManager().popBackStack(); Note: that you will need to know which fragment you are currently displaying so that you can safely call popBackStack on B, C, and D but if you are on A, you will want to (most likely) exit the activity. (Alternatively, you could only pop the back stack if there are items in it. For that, check if (getFragmentManager().getBackStackEntryCount() > 0)

Here's how your full fragment transaction code should look:

// the tag here is if you need to know which fragment is loaded, later
fragmentManager.beginTransaction()
            .replace(R.id.frame_container, fragment, tag).addToBackStack(null).commit();

Then, the back handler:

@Override
public void onBackPressed()
{
    if (someCriteriaToDetermineIfBackStackShouldBePopped)
    {
        getFragmentManager().popBackStack();
        return;
    }
    // this fragment is A (or something else) - let the parent handle the back press
    //  which will finish the activity
    super.onBackPressed();
}

If you need help detecting which fragment is currently loaded, this should get you started: get currently displayed fragment

Community
  • 1
  • 1
kdenney
  • 18,343
  • 4
  • 31
  • 27
  • It perfectly Worked ! Thank you for that detailed answer, you've greatly helped me out ! – Kevin Gilles Jun 06 '14 at 14:46
  • Sure thing; glad I could help! Hope you enjoy developing in Android. – kdenney Jun 06 '14 at 14:53
  • I do, that's really addictive ! Do you have any link of bloggers giving advices on the best practice guidelines that you'd recommend me please ? – Kevin Gilles Jun 06 '14 at 15:04
  • One of the best has to be CommonsWare's blog. http://commonsware.com/blog/ He's also very active here on SO. If you look through enough Android answers, you will come across his name often :) – kdenney Jun 06 '14 at 15:08