我尝试在主布局中替换片段。
在我的主要布局中,我有:
<fragment
android:id="@+id/frame_informations"
android:name="GridFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="2dp"
android:layout_marginEnd="2dp"
app:layout_constraintBottom_toTopOf="@+id/main_bottom_menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/llLit"/>
当我想要替换这个片段时,我使用:
public void switchFrameInformations(Fragment newFragment) {
try {
FragmentTransaction ft = fm.beginTransaction();
// ft.setCustomAnimations(android.R.anim., android.R.anim.fade_out);
if (fm.findFragmentById(R.id.frame_informations) == null) {
ft.add(R.id.frame_informations, newFragment);
} else {
ft.replace(R.id.frame_informations, newFragment);
}
// ft.addToBackStack(null);
ft.commit();
fm.findFragmentById(R.id.frame_informations).getView().requestLayout();
} catch (Exception e) {
e.printStackTrace();
}
}
fm是片段管理器......
这有效,但发生了一些奇怪的事情:新片段包含名称列表,背景是透明的。在替换结束时,我可以在新的背景中看到旧片段......
在调试控制台中,我可以看到所有方法通常都被调用:onDestroy等...用于旧片段。我猜想XML描述中的名称可能会导致问题:
android:name="GridFragment"
但如果没有名字我就无法编译......
据我认为这是一个常见问题,我试图在网上找到解决方案,但我找不到任何解决方案。
谢谢您的帮助。
用<fragment
替换<FrameLayout
在onCreate
的活动中添加以下代码
if (savedInstanceState == null) {
fm.beginTransaction()
.replace(R.id.frame_informations, GridFragment())
.commit();
}
这将正确初始化您的片段,并允许您在代码中轻松切换片段。