4

I have the need to "stack up" fragments one on top of another. I do this by:

    String className = fragment.getClass().getName();

    FragmentManager fragmentManager = getChildFragmentManager();

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.fragment_content, fragment, className);
    fragmentTransaction.addToBackStack(className);
    fragmentTransaction.commit();

Within:

    <FrameLayout
    android:id="@+id/fragment_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" />

This all works good as long as the fragments are of different type.

However if I create a second instance of a fragment type that is already there then there is an exception:

java.lang.IllegalStateException: Fragment already added: TestFragment{1184e8a1 #0 id=0x7f0800ef com.test.ui.TestFragment}

How can I add multiple instances of the same fragment?

One requirement is that they are all on top of each other - because few of them have a small margin that lets you see small portion of the fragment underneath.

Thank you for your help!

user1443656
  • 95
  • 1
  • 6
  • 2
    1) Use different tags for each added fragment. 2) Make sure you add them to a `FrameLayout` (which will stack them on top of each other) not `LinearLayout` (which will put them beside each other). – Eugen Pechanec Feb 26 '15 at 20:29

2 Answers2

1

Layout of parent fragment

<FrameLayout
    android:id="@+id/fragment_contentrow"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

code in parent fragment to add child fragment

 FragmentManager fm = getChildFragmentManager();

    for (int x = 1; x < 5; x = x + 1) {
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragment_contentrow, new MyChildFragment(), "Tag " + x);
        ft.addToBackStack(null);
        ft.commit();
    }
Radheshyam Singh
  • 479
  • 3
  • 10
0

Try to create new instance of your fragment instead of replacing it with the same object over and over again.

fragment = new YourFragment();
fragmentTransaction fragmentTransaction =     fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_content, fragment, className)
    .addToBackStack(className);
    .commit();

Also I suggest to change tags between fragments, for example you can add a number to it.