1

Hi I have read this Difference between add(), replace(), and addToBackStack(). I have a confusion that If I add multiple fragments like below then If I press back button from fragment2 then will fragment1 will open ? If so then what is the use of addToBackStack as add already maintaining a stack.

FragmentTransaction ft = fragmentManager.beginTransaction();

Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");

Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");

ft.commit();
N Sharma
  • 33,489
  • 95
  • 256
  • 444

2 Answers2

3

Well if you call multiple times add method on FragmentTransaction like this

FragmentTransaction ft = fragmentManager.beginTransaction();

Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");

Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");

ft.commit();

then both the fragments that been added to FragmentTransaction will be shown as overlapping.

enter image description here

Now clicking back will close the application. It won't start the previous fragment.

Hope this is what you were looking for.

Mayank Bhatnagar
  • 2,120
  • 1
  • 12
  • 20
1

Add method will not add your Fragment in BackStack. You need to verify once again. While looking into code of addToBackStack

@Override
public FragmentTransaction addToBackStack(String name) {
    if (!mAllowAddToBackStack) {
        throw new IllegalStateException(
                "This FragmentTransaction is not allowed to be added to the back stack.");
    }
    mAddToBackStack = true;
    mName = name;
    return this;
}

Flag mAddToBackStack = true; enabled which value is false by default. And this is the flag which is being used to add fragment into backstack. Have a look into below methods calls

@Override
public int commit() {
    return commitInternal(false);
}

int commitInternal(boolean allowStateLoss) {
    ......
    if (mAddToBackStack) {
        mIndex = mManager.allocBackStackIndex(this);
    } else {
        mIndex = -1;
    }
    .....
}

So what you observed is not correct. Something you are missing

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186