Android,如何替换初始片段?

Android,如何替换初始片段?,android,android-fragments,kotlin,Android,Android Fragments,Kotlin,我创建此片段并设置初始片段FirstFragment,如果我不设置此初始片段,应用程序将崩溃 <fragment android:id="@+id/fragment" android:name="com.app.FirstFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp"

我创建此片段并设置初始片段
FirstFragment
,如果我不设置此初始片段,应用程序将崩溃

<fragment
    android:id="@+id/fragment"
    android:name="com.app.FirstFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp" />

您的问题在于xml内部。不要使用
fagment
标记,您应该创建一个布局,作为片段的容器

按如下方式更改xml:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
val fragment = SettingFragment()
transaction.replace(R.id.fragment_container, fragment)