Bhoomi Zalavadiya
Bhoomi Zalavadiya

Reputation: 689

Add only one instance of fragment into backstack

I have implemented fragments in my application. Here my code for swiching fragment in fragment_container.

 private void switchFragment(Fragment fragment, boolean isAddToBackStack, String tag)
{
    android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

    ft.replace(R.id.container, fragment, tag);
    if (isAddToBackStack)
        ft.addToBackStack(tag);
    setCurrentTopFragment(Integer.parseInt(tag));
    ft.commit();
}

I have 4 fragments A,B,C and D and for switching between this fragmnets I am using above method. I have A,C,B in my backstack. If again I switch to fragmnet A, my backstack is like A,C,B,A. What I actually want is If I swich to A again I want backstack sequence like this C,B,A. Means Remove old instance from backstack and add new to it.

Upvotes: 2

Views: 991

Answers (1)

Charitha Ratnayake
Charitha Ratnayake

Reputation: 379

First get the back-stacked Fragment by id which you need to remove:

Fragment fragment = getSupportFragmentManager().getFragment(new Bundle(), TAG_KEY)

or there are several methods getBackStackEntryCount(), getBackStackEntryAt. After getting the fragment which you need to remove. Remove it from the fragment back-stack.

FragmentManager manager = getActivity().getSupportFragmentManager();    
FragmentTransaction trans = manager.beginTransaction();
trans.remove(fragment);

Then you can add a new fragment Done :)

Upvotes: 1

Related Questions