0

I am creating an application with multiple fragments. I have four fragments fragment1, fragment2, fragment3, fragment4. I am moving from different orders like f1 -> f2 -> f4 -> f3 -> f1 or any other order. But when I click the back button from each fragment I need to go to the previous fragment. How to handle this.

Edit 1: I already tried

 FragmentManager fm = ((Activity) context).getFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
            fm.popBackStack();
        }

Which is not help me to solve my issue.

Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
Amsheer
  • 7,046
  • 8
  • 47
  • 81

7 Answers7

1

Sample code of Manage Fragment back stack

 private Stack<Fragment> stack = new Stack<Fragment>();
 public void pushFragments(Fragment fragment, boolean shouldAnimate,
                          boolean shouldAdd) {

    drawerClose = false;
    if (shouldAdd)
        stack.push(fragment);

    this.changeFragment = fragment;
    invalidateOptionsMenu();
    changeFragment(fragment, shouldAnimate, false);
}

public void popFragments() {
    /*
     * Select the second last fragment in current tab's stack.. which will
     * be shown after the fragment transaction given below
     */
    Fragment fragment = stack.elementAt(stack.size() - 2);
    // / pop current fragment from stack.. /
    stack.pop();
    /*
     * We have the target fragment in hand.. Just show it.. Show a standard
     * navigation animation
     */
    this.changeFragment = fragment;
    invalidateOptionsMenu();
    changeFragment(fragment, false, true);
}

private void changeFragment(Fragment fragment, boolean shouldAnimate, boolean popAnimate) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    if (shouldAnimate)
        ft.setCustomAnimations(R.anim.slide_in_right,
                R.anim.slide_out_left);
    if (popAnimate)
        ft.setCustomAnimations(R.anim.slide_in_left,
                R.anim.slide_out_right);

    ft.replace(R.id.content_frame, fragment);
    ft.commit();
}
//On BackPress just check this thing
    private void backManage() {
    if (stack.size() > 1) {
        popFragments();
    }
}
Akash
  • 961
  • 6
  • 15
  • Your answer is working for me. Only one issue is that if (shouldAdd).. if the fragment is already exists then no need to add the fragments... How to handle it.. – Amsheer Jan 19 '17 at 06:05
  • By getting the Tag of the fragment..You can reuse the previous fragment from the stack.For that you have to pass the "TAG" while adding or replacing the fragment. – Ravindra Kushwaha Jan 19 '17 at 09:48
1

Use addToBackStack(String tag), while committing the fragment to add the fragment into the stack of your application:

getFragmentManager().beginTransaction().replace(fragmentContainer.getID(), fragment)
.addToBackStack(null).commit();`
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Gaurav Chauhan
  • 376
  • 3
  • 14
0

You just need to add addToBackStack(null) by FragmentTransaction. when you are calling next Fragment just add this method with null parameter.

Like this.

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit(); 
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40
0

on Activity

@Override
public void onBackPressed() {
    if(check_if_backstack_is_null)
        super.onBackPressed();
    else
    {
      popupFromBackstack();
    }
}
Pradeep Kumar Kushwaha
  • 2,231
  • 3
  • 23
  • 34
0

You should override onBackPressed method:

@Override
public void onBackPressed() {
  if (fragment != null && fragment.getChildFragmentManager().getBackStackEntryCount() > 0){
     fragment.getChildFragmentManager().popBackStack();
  }else {
    super.onBackPressed();
   }
}
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
0

For this you can set addToBackStack to fragment transation and then call commit. By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.

If you add multiple changes to the transaction (such as another add() or remove()) and call addToBackStack(), then all changes applied before you call commit() are added to the back stack as a single transaction and the Back button will reverse them all together.

Mayank Bhatnagar
  • 2,120
  • 1
  • 12
  • 20
0

Use this lines of code for it:-

    @Override
    public void onBackPressed() {
      if ( getSupportFragmentManager().getBackStackEntryCount() > 0){
         fm.popBackStack();
      }else {
        super.onBackPressed();
       }
    }

To get the backStack functionality in your fragmentthan you should have use the .addToBackStack(null) , while performing the fragment transaction like below:-

           getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.YOUR_CONTAINER, YOUR_FRAGMENT,"TAG")
                        .addToBackStack(null) /// IT IS NECESSARY TO GET THE BACK STACK PROPERTY IN YOUR FRAGMENT
                        .commitAllowingStateLoss();
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103