How to load Jetpack Compose Alert dialog in a fragment is written in Java code?

1.3k views Asked by At

I know we can use composeView to have compose code in the legacy code, but is there any way to use Jetpack Compose Dialog inside java code (especially in a fragment)?

I saw this post Possible to use/layout a compose view in and Activity written in Java? but this is not answer of this question.

I want to show a Jetpack Compose Dialog inside onActivityResult of a fragement in java code!

1

There are 1 answers

2
cutiko On

You have to use ComposeView as indicated in the other question, but make it irrelevant to the layout. Then use setContent to control the dialog.

        <androidx.compose.ui.platform.ComposeView
            android:id="@+id/yourComposeView"
            android:layout_width="0dp"
            android:layout_height="0dp"/>

The trick is the width and height are zero, so it doesn't use space or break the layout.

setContent {
    val showDialog = //you need something here controlled from other place

    if (showDialog) {
        //show the compose dialog here
    }

}

You have to control the visibility with something else like a field in the fragment or in the view model.

val showDialog = MutabaleStateflow(false)

And inside the compose dialog, make that showDialog.value = false when you need to dismiss it.