【问题标题】:Fragment replacement shows the two fragments片段替换显示两个片段
【发布时间】:2019-07-31 12:43:43
【问题描述】:

我尝试替换主布局中的片段。

在我的主要布局中:

<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"

但是如果没有名字就无法编译...

就我认为这是一个常见问题而言,我试图在网上找到解决方案,但我找不到任何解决方案。

感谢您的帮助。

【问题讨论】:

    标签: android android-fragments fragment android-fragmentactivity fragmentmanager


    【解决方案1】:

    将&lt;fragment 替换为&lt;FrameLayout 在onCreate你的activity中添加如下代码

    if (savedInstanceState == null) {
        fm.beginTransaction()
            .replace(R.id.frame_informations, GridFragment())
            .commit();
    }
    

    这将正确初始化您的片段,并允许您在代码中轻松切换片段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多