I am using dataBinding
in my project to populate a RecyclerView
. How can I handle clicks on items?
Here is my XML layout:
<?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>
I specified the onClick
handler in this line:
android:onClick="@{()->clickListener.onCardClick(listItems)}"
And below is my adapter:
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);
}
}
However, the following code doesn't work:
public void onCardClick(String listItems) {
Log.i("SADASSDASDAS", listItems);
}