kotlin 切换 fragment 的最优写法

255 阅读1分钟

布局的写法

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/background_color"
    >
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/bottom_tab_layout"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

对应代码的写法,加入了 tag 缓存获取的方式

private fun switchFragment(fm:Fragment) {
    val tag = fm::class.java.simpleName
    val fmFinal = supportFragmentManager.findFragmentByTag(tag)?:fm
    if (currentFragment == fmFinal) return
    val transaction = supportFragmentManager.beginTransaction()
    currentFragment?.let { transaction.hide(it) }
    if (fmFinal.isAdded) {
        transaction.show(fmFinal)
    } else {
        transaction.add(R.id.fragment_container, fmFinal, tag)
    }
    transaction.commitAllowingStateLoss()
    currentFragment = fmFinal
}