简体   繁体   中英

Android: How to remove fragments from backstack?

I have situation where I want to clear all fragments from backstack except the one which is visible(ie on top)

For example, There are four fragments in backstack A->B->C->D (D is on top)

Now I want to remove fragments A,B,C from backstack. But the constraint is there should not be any visible effect on fragment D while removing history from backstack.

This is my code.

FragmentManager fm = getActivity().getSupportFragmentManager();
                Bundle bundle = new Bundle();
                OrderReceiptFragment orderReceiptFragment = new OrderReceiptFragment();
                bundle.putSerializable("orderHistory", orderHistory);
                orderReceiptFragment.setArguments(bundle);
                CommonUtil.clearBackstack(fm);
                fm.beginTransaction().setCustomAnimations(R.anim.enter_from_left,
                        R.anim.exit_to_right)
                        .replace(R.id.container, orderReceiptFragment).commit();

method to clearbackstack

public static void clearBackstack(FragmentManager fragmentManager) {    
    fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

Here the problem is - while clearing the backstack, for some milliseconds the first fragment from the backstack gets visible. Which looks weird. Does anybody have any solution for this?

YOU CAN DO LIKE THIS

Mehtod 1 :: Removing one by one

 FragmentManager fm = getActivity().getSupportFragmentManager();
      for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
      fm.popBackStack();
}

Mehthod 2

 FragmentManager fm = getActivity().getSupportFragmentManager();
fm .popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

Refer

See this Answer . you can find different methods

Also Refer popBackStackImmediate

这个怎么样-

mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

Try this code:

 FragmentManager _manager = getActivity().getSupportFragmentManager();
_manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

If you are trying to make it so that the only layout in the history at any given time is the one that you are currently viewing, you can do the following in the manifest:

android:noHistory="true"

Put that in for each fragment/activity that you don't want to show up in the history.

Very Simple:

FragmentManager frgManager;
frgManager = getActivity().getSupportFragmentManager();
frgManager.popBackStack("null", FragmentManager.POP_BACK_STACK_INCLUSIVE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM