3

I'm trying to avoid writing extra lines if possible

This works

class ViewModel(val clicked: () -> Unit){
    fun click(){
        clicked()
    }
}

But I would like to write it like this if possible

class ViewModel(val clicked: () -> Unit)

Xml looks like this

android:onClick="@{() -> viewModel.click()}"
or
android:onClick="@{() -> viewModel.clicked()}"

Writing the shorter version fails with cannot find method clicked()

1 Answer 1

1

I believe that with this:

class ViewModel(val clicked: () -> Unit)

Inside your xml, you would have to refer to the invoke method of your lambda.

So something like this:

android:onClick="@{() -> viewModel.clicked.invoke()}"

Edit: or... can't you just use this?

android:onClick="@{viewModel.clicked}"

passing your lambda directly?

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

1 Comment

android:onClick="@{() -> viewModel.clicked.invoke()}" works, thanks

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.