Amsheer
Amsheer

Reputation: 7131

Android fragment handling back button

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.

Upvotes: 0

Views: 1882

Answers (7)

Ravindra Kushwaha
Ravindra Kushwaha

Reputation: 8032

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();

Upvotes: 0

Gaurav Chauhan
Gaurav Chauhan

Reputation: 376

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();`

Upvotes: 1

Vishal Chhodwani
Vishal Chhodwani

Reputation: 2577

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(); 

Upvotes: 0

Mayank Bhatnagar
Mayank Bhatnagar

Reputation: 2191

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.

Upvotes: 0

Satan Pandeya
Satan Pandeya

Reputation: 3815

You should override onBackPressed method:

@Override
public void onBackPressed() {
  if (fragment != null && fragment.getChildFragmentManager().getBackStackEntryCount() > 0){
     fragment.getChildFragmentManager().popBackStack();
  }else {
    super.onBackPressed();
   }
}

Upvotes: 0

Pradeep Kumar Kushwaha
Pradeep Kumar Kushwaha

Reputation: 2239

on Activity

@Override
public void onBackPressed() {
    if(check_if_backstack_is_null)
        super.onBackPressed();
    else
    {
      popupFromBackstack();
    }
}

Upvotes: 0

Akash
Akash

Reputation: 971

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();
    }
}

Upvotes: 1

Related Questions