Last active
February 13, 2020 08:59
-
-
Save realdadfish/6d02dea5ae017e639463bb0250fee2fc to your computer and use it in GitHub Desktop.
getOrAddFragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun <T : Fragment> FragmentActivity.getOrAddFragment(tag: String, commitNow: Boolean = true, initFun: () -> T): T = | |
supportFragmentManager.findFragmentByTag(tag) as? T ?: run { | |
initFun().also { | |
addFragment(supportFragmentManager, tag, commitNow, it) | |
} | |
} | |
fun <T : Fragment> Fragment.getOrAddFragment(tag: String, commitNow: Boolean = true, initFun: () -> T): T = | |
childFragmentManager.findFragmentByTag(tag) as? T ?: run { | |
initFun().also { | |
addFragment(childFragmentManager, tag, commitNow, it) | |
} | |
} | |
private fun addFragment(fragmentManager: FragmentManager, tag: String, commitNow: Boolean, fragment: Fragment) { | |
fragmentManager.transaction(commitNow) { | |
add(fragment, tag) | |
} | |
} | |
fun FragmentManager.transaction(commitNow: Boolean = true, body: FragmentTransaction.() -> Unit) { | |
val transaction = beginTransaction() | |
body(transaction) | |
if (commitNow) transaction.commitNow() else transaction.commit() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyActivity : AppCompatActivity() { | |
override onCreate(state: Bundle) { | |
val fragment = getOrAddFragment(tag = MY_FRAGMENT) { MyFragment() } | |
} | |
companion object { | |
private const val MY_FRAGMENT = "my-fragment" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment