Android Data Binding pass arguments to onClick method

kolodach picture kolodach · May 8, 2016 · Viewed 60.5k times · Source

Is it possible to pass custom arguments to onClick method using the Data Binding Library? I have my layout xml file where I need to use the onClickListener:

<?xml version="1.0" encoding="utf-8"?>
<layout ...>

    <data>
        <variable
            name="viewModel"
            type="com.productivity.tiktak.ui.tracker.viewModel.CategoryViewModel"/>
        <variable
            name="callback"
            type="com.productivity.tiktak.ui.tracker.TrackerAdapter"/>
    </data>

    <android.support.v7.widget.CardView
        android:onClick="@{callback.onCategoryClick(viewModel)}"
        ...
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

       <!-- ... Some stuff -->

    </android.support.v7.widget.CardView>
</layout>

and I a have my click handler code here:

public void onCategoryClick(View view, CategoryViewModel categoryViewModel)
{
    //handler code...
}

Is it possible to pass my CategoryViewModel object from xml to click handler?

Answer

yigit picture yigit · May 8, 2016

You can use a lambda expressions and pass the view in as a parameter.

 android:onClick="@{() -> callback.onCategoryClick(viewModel)}"

If you need the view, you can pass that as well with:

 android:onClick="@{(view) -> callback.onCategoryClick(view, viewModel)}"