新建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
网友评论