سؤال

What happen if a add to BackStack a fragment that is already inside it? For example:

Fragment one = new Fragment();
Fragment two = new Fragment();

getSupportFragmentManager().beginTransaction().add(R.id.viewGroup, one).addToBackStack(null).commit();
//...
getSupportFragmentManager().beginTransaction().replace(R.id.viewGroup, two).addToBackStack(null).commit();
//...
getSupportFragmentManager().beginTransaction().replace(R.id.viewGroup, one).addToBackStack(null).commit();

When i add again fragment "one", two references to it is inside stack or only lastest is mantained ?

هل كانت مفيدة؟

المحلول

Even through the instance of the fragment is same, the BackStack entry will be increased, when an already exist Fragment is added to BackStack again.

When you add First Fragment , the back stack entry will be one.

When you replace Second Fragment ,the back stack entry will be two

When you replace First Fragment ( even though the same First Fragment instance), The older (first) Fragment instance will be reused. but the BackStack entry will be three

Now the stack will look like this

`First Fragment` -> `Second Fragment` -> `First Fragment`

So when Back pressed Fragments will be popped out as Fist Fragment , then Second Fragment and then again First Fragment.

This is the addBackStackState method in FragmentManager

 void addBackStackState(BackStackRecord state) {
    if (mBackStack == null) {
        mBackStack = new ArrayList<BackStackRecord>();
    }
    mBackStack.add(state);
    reportBackStackChanged();
}

You can look at the BackStackRecord class to understand more how addBackStackState method is called.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top