我目前正在尝试在Viewpager片段中包含2个片段。 一切正常,但是如果我进一步滚动2个片段并返回到具有两个片段的片段,则只有上片段可见(片段B不可见)。如果我再次这样做,两者都会再次出现。 onResume-Event在片段B中调用,但未显示。 布局XML:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/a_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/android_color_blue_dark"/>
<FrameLayout
android:id="@+id/b_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/android_color_green_dark" />
</LinearLayout>
onCreateView()
中的父片段代码 if (v.findViewById(R.id.a_fragment) != null) {
FragmentManager mgr = getChildFragmentManager();
Fragment f = mgr.findFragmentByTag(TAG_A_FRAGMENT);
if (f == null) {
f = new FragmentA();
}
FragmentTransaction transaction = mgr.beginTransaction();
transaction.replace(R.id.a_fragment, f, TAG_S_FRAGMENT);
transaction.commit();
}
if (v.findViewById(R.id.b_fragment) != null) {
FragmentManager mgr = getChildFragmentManager();
Fragment f = mgr.findFragmentByTag(TAG_B_FRAGMENT);
if (f == null) {
f = new FragmentBLogin();
}
FragmentTransaction transaction = mgr.beginTransaction();
transaction.replace(R.id.b_fragment, f,
TAG_B_FRAGMENT);
transaction.commit();
}
我会动态添加这些片段,即使它们是静态的以防止此Error。
答案 0 :(得分:0)
我修正如下。现在没有解释为什么它以这种方式工作而不是其他方式。
if (v.findViewById(R.id.a_fragment) != null) {
FragmentManager mgr = getChildFragmentManager();
Fragment f = mgr.findFragmentByTag(TAG_A_FRAGMENT);
if (f == null) {
f = new FragmentA();
FragmentTransaction transaction = mgr.beginTransaction();
transaction.replace(R.id.a_fragment, f, TAG_S_FRAGMENT);
transaction.commit();
}
}
if (v.findViewById(R.id.b_fragment) != null) {
FragmentManager mgr = getChildFragmentManager();
Fragment f = mgr.findFragmentByTag(TAG_B_FRAGMENT);
if (f == null) {
f = new FragmentBLogin();
FragmentTransaction transaction = mgr.beginTransaction();
transaction.replace(R.id.b_fragment, f,
TAG_B_FRAGMENT);
transaction.commit();
}
}