Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
527 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...