我正在尝试将同一 fragment 的多个实例添加到一个 Activity 中。示例代码是
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();
当 Activity 运行时,只添加了一个 fragment 实例 - 为什么?
有关信息, fragment 被插入到 Activity 的 XML 布局中,并且 代码中引用的R.id.fragment_content定义为:
<FrameLayout
android:id="@+id/fragment_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
最佳答案
问题似乎是使用 FrameLayout
作为 fragment 的容器。我将其更改为
<LinearLayout
android:id="@+id/fragment_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
现在可以正常工作了。
关于android - 添加同一 fragment 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349816/