3

Android DataBinding / BindingAdapter Error: An error is thrown: error: missing return statement when passing a function to BindingAdapter (block: () -> Unit).

BindingAdapter.kt

@BindingAdapter("click")
fun LottieAnimationView.click(block: () -> Unit) {
    setOnClickListener {
        block()
    }
}

activity_main.xml

<data>
    <variable
        name="viewModel"
        type="com.veldan.ViewModel" />
</data>

<View
        android:id="@+id/view"
        click="@{() -> viewModel.viewFun()}"
        android:layout_width="0dp"
        android:layout_height="0dp"   />

<View
        android:id="@+id/view"
        click="@{() -> viewModel.viewFun()}"
        android:layout_width="0dp"
        android:layout_height="0dp"   />

ViewModel.kt

class ViewModel() {
     viewFun(){
        // logic
     }
}

1 Answer 1

6

SOLUTION 1:

Use Field syntax


  • Function syntax: ❌

| click = "@{ () -> viewModel.viewFun() }"

  • Field syntax: ✅

| click = "@{ viewModel.viewFun }"


SOLUTION 2:

Use Lambda

| ViewModel.kt

class ViewModel() {
    val viewFun: () -> Unit = {
        // logic
     }
}

Lambda - works well when block with parameters.

| block with parameters

@BindingAdapter("click")
fun LottieAnimationView.click(block: (Param1, Param2, ...) -> Unit) {
    setOnClickListener {
        block()
    }
}

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

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.