Manoj Srivastava
Manoj Srivastava

Reputation: 670

PopBackStack is not working properly

I have coded like this:

FragA >> FragB >> FragC >> FragD

When I press onBackpress() of FragD it goes to directly on FragA but i want to keep it go FragC.

BackPress Code here :

 if (getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) {
            back_btn.setVisibility(View.GONE);
            getActivity().getSupportFragmentManager().popBackStack();
        }

Replacing Fragment Code :

                       FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                       FragmentA fragmentA = new FragmentA();
                       fragmentTransaction.replace(R.id.framelayoutinner, fragmentA);
                       fragmentTransaction.addToBackStack("fragmentA");
                       fragmentTransaction.commit();



                       FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                       FragmentA fragmentB = new Fragmentb();
                       fragmentTransaction.replace(R.id.framelayoutinner_2, fragmentB);
                       fragmentTransaction.addToBackStack("fragmentB");
                       fragmentTransaction.commit();

Upvotes: 0

Views: 3808

Answers (2)

Rahul
Rahul

Reputation: 10635

You are using nested fragments, if you load fragment from another fragment then it become nested structure. So try to check if any child fragment exist within your Root fragment then pop that child fragment first.

Use getChildFragmentManager() for that and make recursive calls till you get most young child fragment(Last added). Or better use Tag on your fragments.

Upvotes: 1

Reena
Reena

Reputation: 1378

You need to add every fragment into backstack using addToBackStack method

  public void setmFragmentContainer(Fragment fragment)
    {
        final String tag = fragment.getClass().getName();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.layout_content, fragment, tag);
        transaction.addToBackStack(tag);
        transaction.commit();
    }

This method may help you

Upvotes: 0

Related Questions