使用 android DataBinding 库如何将参数传递给绑定事件

Using android DataBinding library how to pass parameters to binding events

我遵循了 Android 开发人员 Binding Events 的示例并逐步实施。那工作正常。但是我想将参数从适配器发送到处理程序,如何使用数据绑定处理程序来实现这一点

我得到了答案。 在 xml 中,对于 onclick 使用 lambda 表达式

layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="movie"
        type="embitel.com.databindingexample.helper.Movie" />

    <variable
        name="handler"
        type="embitel.com.databindingexample.helper.MyHandlers" />

</data>

<android.support.v7.widget.CardView
    android:id="@+id/cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="4dp"
    android:onClick="@{(view)->handler.onItemClicked(view,movie)}"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="128dp"
            android:scaleType="centerCrop"
            app:error="@{@drawable/ic_launcher}"
            app:imageUrl="@{movie.imageUrl}" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{movie.title}" />

    </LinearLayout>

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

然后创建处理程序 class 作为,

public class MyHandlers {

public void onItemClicked(View v, Movie movie) {
    Context context = v.getContext();
    context.startActivity(DetailActivity.buildIntent(context, movie));
}

}

然后你需要设置处理程序,其中 xml 被 iflated 为,

binding.setHandler(new MyHandlers());

您还可以将处理程序方法放在任何 class 中。在这种情况下,您必须将 class 名称设置为处理程序。