【问题标题】:Fragment still visible after popBackStackImmediate and replace在 popBackStackImmediate 和替换后片段仍然可见
【发布时间】:2018-03-09 06:24:55
【问题描述】:

我的后台堆栈上有fragmentA,屏幕上有fragmentB。我想用fragmentC替换fragmentB,这样当用户按下时,我们回到fragmentA。这就是我用fragmentC替换fragmentB的方式

    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content_container, fragment);
    transaction.commitAllowingStateLoss();

这就是我处理后按的方式

    final FragmentManager fm = getSupportFragmentManager();
    if (fm.getBackStackEntryCount() != 0) {
        fm.popBackStackImmediate();
    } else {
        super.onBackPressed();
    }

用fragmentC替换fragmentB后,当按下后退按钮时fragmentA会显示,但fragmentC仍然在屏幕上可见,这给了我一些非常奇怪的UI。有谁知道为什么会这样??

【问题讨论】:

  • 可以向我们展示完整的代码,您在其中为“片段”等赋值。你是在使用带有标签视图还是抽屉视图的片段?

标签: java android android-fragments android-lifecycle fragment-backstack


【解决方案1】:

将交易添加到后台:

final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.content_container, fragment); transaction.addToBackStack("") transaction.commitAllowingStateLoss();

【讨论】:

    【解决方案2】:

    如果我理解正确,FragmentA 会覆盖在 FragmentC 上,因此两个片段都是可见的。

    如果是这种情况,请在 xml 布局中设置片段 A 和 C 的背景。这是一个例子

    片段A

    <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tool="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="#FFF"
         android:orientation="vertical">
    
        //Fragment A contents
    
    </LinearLayout>
    

    片段C

    <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tool="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="#FFF"
         android:orientation="vertical">
    
         //Fragment C contents
    
      </LinearLayout>
    

    观察两个片段在它们的根视图中都设置了背景属性。因此,尽管它们被覆盖,但一次只能看到一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 2013-05-22
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多