我遵循了来自 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/