Android,如何替换初始片段?

时间:2018-07-23 09:22:14

标签: 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"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp" />

然后我使用此函数替换片段,这工作正常,每个片段都可以被FirstFragment以外的其他片段替换,该片段一直显示在屏幕上。如何替换此片段?

enum class FragmentType {
    SETTING, ACTIVITY, PROFILE, CONNECT, SCANNER
}
private fun changeFragmentTo(type: FragmentType) {
    val transaction = supportFragmentManager.beginTransaction()
    when(type) {
        FragmentType.SETTING -> {
            title = "SETTING"
            val f = SettingFragment()
            transaction.replace(R.id.fragment, f)
        }

        FragmentType.ACTIVITY -> {
            title = "ACTIVITY"
            val f = ActivityFragment()
            transaction.replace(R.id.fragment, f)
        }

        FragmentType.PROFILE -> {
            title = "PROFILE"
            val f = ProfileFragment()
            transaction.replace(R.id.fragment, f)
        }
        FragmentType.CONNECT -> {
            title = "CONNECT"
            val f = ConnectFragment()
            transaction.replace(R.id.fragment, f)
        }
        FragmentType.SCANNER -> {
            title = "SCANNER"
            val f = ScannerFragment()
            transaction.replace(R.id.fragment, f)
        }

    }
    transaction.addToBackStack(null)
    transaction.commit()
}

1 个答案:

答案 0 :(得分:1)

您的问题在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" />

并通过其ID FrameLayout引用您的R.id.fragment里面的活动:

val fragment = SettingFragment()
transaction.replace(R.id.fragment_container, fragment)