android-databinding - 使用android DataBinding库如何将参数传递给绑定(bind)事件

标签 android-databinding

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

最佳答案

我得到了答案。
在用于 onclick 的 xml 中使用 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>

然后创建处理程序类,
public class MyHandlers {

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

}

那么您需要设置处理程序,该 xml 被定义为,
binding.setHandler(new MyHandlers());

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

关于android-databinding - 使用android DataBinding库如何将参数传递给绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37828354/

相关文章:

android - Android Studio 2.2.1 中使用约束布局的布局编辑器问题

android - 布局表达式中可绘制对象的三元运算符

kotlin - 在使用 Android 数据绑定(bind)和 Kotlin 的自定义 BindingAdapter 中使用 lambda

java - Android 数据绑定(bind)错误示例

android - 设计 View 中的数据绑定(bind)

android - 数据绑定(bind)在等待 Android 中填充值时显示未填充的值

android - android 绑定(bind)应用程序中的自定义事件属性 :onMyEvent

android - ViewDataBinding getVariable?

android-studio - Android Studio 在使用 DataBinding 时无法生成 Binding 类

android - BindingAdapter 弃用警告