Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Last active June 3, 2021 07:24
Show Gist options
  • Save marcellogalhardo/b70d875a6b5d1128ab0438783ecc135d to your computer and use it in GitHub Desktop.
Save marcellogalhardo/b70d875a6b5d1128ab0438783ecc135d to your computer and use it in GitHub Desktop.
Convenience FragmentManager extension functions.
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.fragment.app.FragmentManager
/**
* Create a new instance of a [Fragment] with the given class name. This uses
* [FragmentFactory.loadFragmentClass] and the empty constructor of the resulting
* [Class] by default.
*
* This is a convenience for explicitly creating the fragment with [FragmentFactory],
* passing the classLoader and className, and casting to the right fragment type.
*/
inline fun <reified T : Fragment> FragmentManager.instantiate(
block: (fragment: T) -> Unit = {},
): T {
val classLoader = requireNotNull(T::class.java.classLoader)
return (fragmentFactory.instantiate(classLoader, T::class.java.name) as T).apply(block)
}
/**
* Display the dialog, adding the fragment to the [FragmentManager].
*
* This is a convenience for explicitly creating the fragment and transaction,
* adding the fragment to it with the given tag, and committing it
*
* This does **not** add the transaction to the fragment back stack. When the
* fragment is dismissed, a new transaction will be executed to remove it from
* the activity.
*/
inline fun <reified T : DialogFragment> FragmentManager.showDialog(
tag: String? = null,
block: (dialog: T) -> Unit = {},
) {
instantiate<T>().apply(block).show(this, tag)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment