归类 : Android Kotlin

定义扩展函数便捷添加Fragment到Activity中

Java - 添加一个Fragment到Activity的代码

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(frameId, fragment);
    transaction.commit();

Kotlin代码

kotlin的扩展函数(Extension function)为类添加新函数提供能方便的实现

1. 为FragmentManager类写一个扩展函数

        inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
                val fragmentTransaction = beginTransaction()
                fragmentTransaction.func()
                fragmentTransaction.commit()
        }

使用这个扩展函数

            supportFragmentManager.inTransaction {
                add(R.id.frameLayoutContent, fragment)
        }

2. 扩展FragmentActivity

    fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int, backStackTag: String? = null) {
            supportFragmentManager.inTransaction {
                    add(frameId, fragment)
                    backStackTag?.let { addToBackStack(fragment.javaClass.name) }
            }
    }
    fun AppCompatActivity.replaceFragment(fragment: Fragment, frameId: Int, backStackTag: String? = null) {
            supportFragmentManager.inTransaction {
                    replace(frameId, fragment)
                    backStackTag?.let { addToBackStack(fragment.javaClass.name) }
            }
    }

现在即可方便的使用以上方法add或replace Fragment

    addFragment(yourFragment, R.id.frameLayoutContent, "tag")
    replaceFragment(yourFragment, R.id.frameLayoutContent, "tag")

以上