当前位置: 首页 > 工具软件 > Android KTX > 使用案例 >

android_基础_ktx之获取fragment(show方案)

林正平
2023-12-01

转载自:https://www.jianshu.com/p/3490ec0eed34

android ktx之获取fragment(show方案)

inline fun <reified T : Fragment> FragmentActivity.showFragment(replaceViewId: Int) : T{
    val sfm = supportFragmentManager
    val transaction = sfm.beginTransaction()
    varinline fun <reified T : Fragment> 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 <reified T : Fragment> FragmentActivity.getFragment(
        init: (T)?.() -> Unit = {}): T? {
    val fragment = supportFragmentManager.findFragmentByTag(T::class.java.name)
    init(fragment as T?)
    return fragment
}

用法

//括号内为要替换成fragment的布局id
showFragment<SearchFragment>(R.id.flFragmentContainer)
//后面直接跟大括号可以初始化fragment
 类似资料: