RecyclerView Databinding Item click
You’ll first need an interface that specifies listener’s behavior. In this example, there is a sample model called ContentItem, so the click will return an item of that type:
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
The constructor will receive an object that implements this interface, along with the items to be rendered:
private final List<ContentItem> items;
private final OnItemClickListener listener;
public ContentAdapter(List<ContentItem> items, OnItemClickListener listener) {
this.items = items;
this.listener = listener;
}
You could alternatively create a setOnItemClickListener method and assign it that way. Now, in onBindViewHolder the ViewHolder will receive the constructor in the custom bind method:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), listener);
}
This is how this bind method looks:
public void bind(final ContentItem item, final OnItemClickListener listener) {
...
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
Use it whenever you need it by creating a new adapter and the listener that will implement the behavior when an item is clicked. A simple example:
recycler.setAdapter(new ContentAdapter(
items,
new ContentAdapter.OnItemClickListener() {
@Override
public void onItemClick(ContentItem item) {
Toast.makeText(getContext(), "Item Clicked", Toast.LENGTH_LONG).show();
}
}));
Source