Skip to content

Instantly share code, notes, and snippets.

@ahndwon
Last active April 4, 2021 03:08
Show Gist options
  • Save ahndwon/d08c2ac85e6604d3dadfb79d58d445a2 to your computer and use it in GitHub Desktop.
Save ahndwon/d08c2ac85e6604d3dadfb79d58d445a2 to your computer and use it in GitHub Desktop.
inline fun <reified T : Fragment> FragmentManager.replaceFragment(
@IdRes containerViewId: Int,
vararg param: Pair<String, Any?>,
tag: String = T::class.java.simpleName
): T? {
return findFragment() ?: T::class.java.newInstance().also { newFragment ->
newFragment.arguments = bundleOf(*param)
beginTransaction()
.replace(containerViewId, newFragment, tag)
.commitAllowStateLoss()
}
}
inline fun <reified T : Fragment> FragmentManager.findFragment(
tag: String = T::class.java.simpleName
): T? {
return findFragmentByTag(tag) as? T
}
inline fun <reified T : Fragment> FragmentActivity.replaceFragment(
@IdRes containerViewId: Int,
vararg param: Pair<String, Any?>,
tag: String = T::class.java.simpleName
): T? {
return supportFragmentManager.replaceFragment(containerViewId, *param, tag = tag)
}
inline fun <reified T : Fragment> FragmentActivity.findFragment(
tag: String = T::class.java.simpleName
): T? {
return supportFragmentManager.findFragment(tag)
}
inline fun <reified T : Fragment> Fragment.replaceFragment(
@IdRes containerViewId: Int,
vararg param: Pair<String, Any?>,
tag: String = T::class.java.simpleName
): T? {
return childFragmentManager.replaceFragment(containerViewId, *param, tag = tag)
}
inline fun <reified T : Fragment> Fragment.findFragment(
tag: String = T::class.java.simpleName
): T? {
return childFragmentManager.findFragment(tag)
}
/**
companion object {
private const val ARG_KEY1 = "key1"
private const val ARG_KEY2 = "key2"
fun show(
fragmentManager: FragmentManager,
@IdRes containerViewId: Int,
value1: String,
value2: String
): DestinationFragment? {
return fragmentManager.replaceFragment(
containerViewId,
ARG_KEY1 to value1,
ARG_KEY2 to value2
)
}
}
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment