我正在我的项目中使用 dataBinding
来填充一个 RecyclerView
。我该如何处理项目的点击事件?
这是我的 XML 布局:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="listItems"
type="String" />
<variable
name="clickListener"
type="com.xxxx.xxxx.AdapterStartActivity" />
</data>
<android.support.v7.widget.CardView
android:id="@+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:onClick="@{()->clickListener.onCardClick(listItems)}" <=====
card_view:cardCornerRadius="7dp"
card_view:cardElevation="7dp"
card_view:cardMaxElevation="7dp"
card_view:contentPadding="0dp">
<TextView
android:id="@+id/txtTitles"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:padding="10dp"
android:text="@{listItems}"
android:textColor="#000000"
android:textSize="20dp"
android:textStyle="bold" />
</android.support.v7.widget.CardView>
</layout>
我在这一行中指定了onClick
处理程序:
android:onClick="@{()->clickListener.onCardClick(listItems)}"
以下是我的适配器:
public class AdapterStartActivity extends RecyclerView.Adapter<AdapterStartActivity.ViewHolder> {
private ListItemActivityStartBinding binding;
private List<String> listTitle;
private Context context;
public AdapterStartActivity(Context context, List<String> listTitle) {
this.listTitle = listTitle;
this.context = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtTitles;
public ViewHolder(View v) {
super(v);
txtTitles = (TextView) v.findViewById(R.id.txtTitles);
}
}
@Override
public AdapterStartActivity.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item_activity_start, parent, false);
binding = DataBindingUtil.bind(view);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder Vholder, int position) {
binding.setListItems(listTitle.get(position));
}
@Override
public int getItemCount() {
return listTitle.size();
}
public void onCardClick(String listItems) {
Log.i("SADASSDASDAS", listItems);
}
}
然而,以下代码无法正常工作:
public void onCardClick(String listItems) {
Log.i("SADASSDASDAS", listItems);
}
RecyclerView.ViewHolder
有几种获取位置信息的方法,最常用的是ViewHolder.getAdapterPosition()
。 - Uli