2

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 !

2
  • 1
    Compose is kotlin only, I guess you can't use anything @Composable annotated from java. Commented May 30, 2022 at 2:44
  • You can't. stackoverflow.com/questions/66433437/… Commented May 30, 2022 at 3:17

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.