1

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 Answers1

0

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.

cutiko
  • 9,887
  • 3
  • 45
  • 59
  • But what if you are converting legacy common code? For example, you might have a simple function that takes a `Context` and displays an `AlertDialog`. That could be called from any 'screen'. It doesn't seem obvious how to migrate such functions. – Mark Jan 22 '23 at 03:08
  • 1
    It is not obvious because `ComposeView` is a element for migrating the project. For example in the nav graph docs it is explained that navigation apprpach is an all or nothing, is either fragment way or compose way. You still can have something like that. Add the `ComposeView` in the underlying common `Activity` and then expose a `Flow` so other can trigger the dialog. – cutiko Jan 23 '23 at 08:39