Android kotlin fragment 切换代码(show方案)

新建kt文件,复制以下代码:

inline fun  FragmentActivity.showFragment(replaceViewId: Int) : T{
    val sfm = supportFragmentManager
    val transaction = sfm.beginTransaction()
    varinline fun  FragmentActivity.showFragment(
        replaceViewId: Int, init: (T).() -> Unit = {}): T {
    val sfm = supportFragmentManager
    val transaction = sfm.beginTransaction()
    var fragment = sfm.findFragmentByTag(T::class.java.name)
    if (fragment == null) {
        fragment = T::class.java.newInstance()
        transaction.add(replaceViewId, fragment, T::class.java.name)
    }
    sfm.fragments.filter { it != fragment }.forEach { transaction.hide(it) }
    transaction.show(fragment)
    transaction.commitAllowingStateLoss()
    sfm.executePendingTransactions()
    init(fragment as T)
    return fragment
}

inline fun  FragmentActivity.getFragment(
        init: (T)?.() -> Unit = {}): T? {
    val fragment = supportFragmentManager.findFragmentByTag(T::class.java.name)
    init(fragment as T?)
    return fragment
}

用法:

//括号内为要替换成fragment的布局id
showFragment(R.id.flFragmentContainer)
//后面直接跟大括号可以初始化fragment

你可能感兴趣的:(Android kotlin fragment 切换代码(show方案))