Last active
April 4, 2021 03:08
-
-
Save ahndwon/d08c2ac85e6604d3dadfb79d58d445a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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