Arik6
Arik6

Reputation: 123

Call Jetpack Compose element from a java file

I'm trying to use Jetpack Compose UI element in the existed XML from the activity, using databinding and setContent(). This is the xml element:

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

I'm use this syntax in kotlin activity file and it works smoothly:

binding.ComposeView.setContent{
    MainActionButtonKt.MainActionButton(true, R.string.complete_job, R.drawable.ic_complete_btn_icon, false);
}

(got it from android's duc)

What is the equivalent for java activity file? I I tried to do that:

binding.saveBtnCompose.setContent((composer, integer) -> {
     MainActionButton(true, R.string.complete_job, R.drawable.ic_complete_btn_icon, false);
     return null;
});

but I got a compile error:

required: boolean, int, Integer, boolean, Composer, int, int
found:    boolean, int, int,     boolean

reason: actual and formal argument lists differ in length

What am I doing wrong? Thanks !

Upvotes: 2

Views: 3690

Answers (2)

Carson Holzheimer
Carson Holzheimer

Reputation: 2963

Building on the above answer, if you want to use the equivalent to setContent without the need for first setting an xml layout, you can write a glue function like this:

fun setContentToMyScreen(activity: ComponentActivity, myParam: Boolean) {
    activity.setContent {
        MyScreen(myParam)
    }
}

@Composable
fun MyScreen(myParam: Boolean) {
    ...
}

That can then be called from a java Activity like so in onCreate:

setContentToMyScreen(this, true);

Upvotes: 0

user19777496
user19777496

Reputation: 61

You can use.

Create a kotlin function at anywhere else

fun setContent(composeView:ComposeView, composeparam1: Boolean){
    composeView.setContent {
        CallYourComposeFunction(composeparam1)
    }
}

Then call this from your java code by giving composeView from xml.

Upvotes: 6

Related Questions