Adding multiple instances of the same fragment

2019-02-26 23:21发布

问题:

I am attempting to add multiple instances of the same fragment to an activity. Example code is

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_content);

    FragmentTransaction ft = fm.beginTransaction();

    for (int x = 1; x < 5; x = x + 1) {
        Log.i("frag","x="+x);
        ft.add(R.id.fragment_content, new SpecimenFragment(),"x_"+x);           
    }

    ft.commit();

When the activity runs there is only one instance of the fragment added - why?

For info the fragments are being inserted into an XML layout for the activity and the R.id.fragment_content referenced in the code is defined as :

<FrameLayout
    android:id="@+id/fragment_content"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

回答1:

The problem seemed to be is using the FrameLayout as the container for the fragments. I change this to

<LinearLayout
    android:id="@+id/fragment_content"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" />

and it now works fine.