https://kotlinlang.org logo
#compose
Title
# compose
m

Mark

02/03/2023, 1:53 PM
This is the code I wrote to help migration from using `AlertDialog`s old-style (but not
DialogFragment
) to Compose. The viewtree stuff I found by trial and error, so please let me know if there’s a better way:
Copy code
fun Fragment.showDialog(dialogContents: @Composable (onDismissRequest: () -> Unit) -> Unit): AlertDialog? {
    val activity = activity ?: return null
    if (activity.isFinishing) {
        return null
    }
    val view = view ?: return null
    var dialog: AlertDialog? = null
    dialog = MaterialAlertDialogBuilder(activity).apply {
        setView(
            ComposeView(activity).apply {
                // doesn't seem to do make a difference, so commenting out
                // setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
                setContent {
                    MdcTheme(setTextColors = true) {
                        dialogContents {
                            dialog?.cancel()
                        }
                    }
                }
            }
        )
    }.show()
    val decView = dialog.window?.decorView ?: return null
    decView.setViewTreeLifecycleOwner(view.findViewTreeLifecycleOwner())
    decView.setViewTreeViewModelStoreOwner(view.findViewTreeViewModelStoreOwner())
    decView.setViewTreeSavedStateRegistryOwner(view.findViewTreeSavedStateRegistryOwner())
    return dialog
}