片段在弹出后仍然可见 BackStack立即和替换



我的后备堆栈上有片段A,屏幕上有片段B。我想用片段C替换片段B,这样当用户按下后退时,我们回到片段A。这就是我用片段C替换片段B的方式

    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();
    }

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

将事务添加到后退堆栈:


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

没看错的话,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>

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

最新更新