美文网首页
Android kotlin fragment 切换代码(sho

Android kotlin fragment 切换代码(sho

作者: JarryLeo | 来源:发表于2019-05-28 16:23 被阅读0次

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

    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
    

    相关文章

      网友评论

          本文标题:Android kotlin fragment 切换代码(sho

          本文链接:https://www.haomeiwen.com/subject/skbdtctx.html