How to load jetpack compose from java activity

706 views Asked by At

How to load jetpack compose from java activity?

I have java activity:

@Override
    public void onCreate(Bundle savedInstanceState) {

but on the button click I want to open @Composable function.

I'm calling it from java via

fun setContent(activity: AppCompatActivity){
        activity.setContent {
                CustomDialog() // contains Dialog
        }
    }

But this composable function destroy my previous view.

How can I open this custom dialog on the previous view?

2

There are 2 answers

0
Slava On BEST ANSWER

found only such solution:

class JetPackDialog() : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                JetPackDialogView()
                }
            }
        }
}
0
Cam Horsley On

Found the answer in a related post. Took me hours of searching to find it... Possible to use/lay out a Compose view in an Activity written in Java?

You don't necessarily need the AbstractComposeView. I was able to do this just with the following:

Add ComposeView to your layout.xml just as you would any other View:

<androidx.compose.ui.platform.ComposeView
     android:id="@+id/compose_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>

Create a new kt file, for example ComposeFunctions.kt that has a function to set the content to the ComposeView:

@file:JvmName("ComposeFunctions")
 
 package (your package goes here)
 
 fun setContent(composeView: ComposeView) {
     composeView.setContent { composable kt function goes here } }

Now from your java Activity/Fragment

ComposeView composeView = view.findViewById(R.id.compose_view);
 ComposeFunctions.setContent(composeView); 

I have used this successfully on WearOS for androidx.wear.compose.material.TimeText:

composeView.setContent { TimeText() }