且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

过渡后,第一个片段仍保留在背景中

更新时间:2021-11-04 22:23:38

问题是您无法替换通过< fragment> 标记添加的片段.

The problem is that you cannot replace fragments added via the <fragment> tag.

相反,您应该:

1)切换到 FragmentContainerView ,它已添加到

1) Switch to FragmentContainerView, which was added in Fragment 1.2.0. It does not suffer from the same issue as the <fragment> tag and lets you do replace operations without issues:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".StartActivity"
    android:background="@mipmap/background">

    <androidx.fragment.app.FragmentContainerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewpagerstart"
        android:layout_centerInParent="true"
        android:name="com.example.distributedsystemsui.SplashFragment">

    </androidx.fragment.app.FragmentContainerView>
</RelativeLayout>

2)在布局中使用 FrameLayout 并在活动中手动添加 SplashFragment (这实际上是 FragmentContainerView 为您执行的操作):

2) Use a FrameLayout in your layout and manually add the SplashFragment in your activity (this is essentially what FragmentContainerView does for you):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".StartActivity"
    android:background="@mipmap/background">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewpagerstart"
        android:layout_centerInParent="true">

    </FrameLayout>
</RelativeLayout>

这意味着您需要手动添加SplashFragment:

which means you need to add the SplashFragment manually:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
            .add(R.id.viewpagerstart, new SplashFragment())
            .commit()
    }
}