首页 文章

在popBackStackImmediate和replace之后片段仍然可见

提问于
浏览
1

我的backstack上有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 . 任何人都知道为什么会这样吗?

2 回答

  • 0

    如果我找到你,FragmentA会叠加在FragmentC上,因此两个片段都是可见的 .

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

    FragmentA

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

    FragmentC

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

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

  • 0

    将事务添加到backstack:

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

相关问题