How to pop fragment off backstack

左心房为你撑大大i 提交于 2019-12-27 20:00:33

问题


I have an activity A, which calls fragment Bf, which calls fragment Cf. I want Bf to be placed in the backstack when Cf is called so that users can navigate back to it. However, if a specific button is pressed in Cf, I would like Bf to be removed from the backstack. Is this possible?

I see that there is a popBackStack() function. However, I am a little confused on how this would work. Is it safe to use this function? Is there any possibility that an activity from a different application would be inserted after Bf on the backstack?

Also, is there any way to alter the savedInstanceState of the fragment on the backstack?

I just can't figure out how to do a robust test on the backstack using the emulator.


回答1:


You can pop the fragment by name. While adding fragments to the back stack, just give them a name.

fragmentTransaction.addToBackStack("fragB");
fragmentTransaction.addToBackStack("fragC");

Then in Fragment_C, pop the back stack using the name ie.. fragB and include POP_BACK_STACK_INCLUSIVE

someButtonInC.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        FragmentManager fm = getActivity()
                .getSupportFragmentManager();
        fm.popBackStack ("fragB", FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
});



回答2:


Three Way To pop Fragment off BackStack

Simply Add This Line

1. getActivity().getSupportFragmentManager().popBackStack();

2. getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

3. getActivity().getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

its all easy way to pop fragment off backstack




回答3:


first replacing fragment container_view that time we add name as like "Later Transaction"

   getSupportFragmentManager().beginTransaction().replace(R.id.container_view, 
    profileFragment, "Profile").addToBackStack("Later Transaction").commit();

then on back press button pop the back stack using the Later Transaction name

     int count = getSupportFragmentManager().getBackStackEntryCount();
    if(count > 1) {
     getSupportFragmentManager().popBackStack("Later Transaction", 
     FragmentManager.POP_BACK_STACK_INCLUSIVE);
    } else {
        DialogUtils.show(HomeActivity.this, 
        getString(R.string.exit_app_message), getString(R.string.alert), 
       "Yes","No", new DialogUtils.ActionListner() {
            @Override
            public void onPositiveAction() {
                finish();
            }
            @Override
            public void onNegativeAction() {
            }
        });
    }


来源:https://stackoverflow.com/questions/14971780/how-to-pop-fragment-off-backstack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!