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

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

java - Android Data Binding pass arguments to onClick method

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...