I have an ImageView in CardViews of my RecyclerView. I would like to catch the onClick on the ImageView, like I already did with the ListView. So, in the public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) I tried with:
myViewHolder.imageView.setClickable(true);
myViewHolder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("TEST", "Clicked");
}
but this was totally ignored. The following code is working:
myViewHolder.imageView.setImageResource(R.drawable.star_yellow);
What can I do?
Where do you add the android:onClick attribute to make items in a RecyclerView respond to clicks? In the layout file that displays the RecyclerView, add it to the element. Add it to the layout file for an item in the row.
A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive findViewById results. While LayoutParams belong to the LayoutManager , ViewHolders belong to the adapter.
Here's what I do in my project.
Have an interface class somewhere in your project:
public interface RecyclerViewClickListener {
void onRowClicked(int position);
void onViewClicked(View v, int position);
}
In your RecyclerView.Adapter class, add this interface as a field and pass it to adapter via constructor:
public class YourRecAdapter extends RecyclerView.Adapter<YourRecAdapter.SimpleViewHolder>{
private RecyclerViewClickListener listener;
public YourRecAdapter(RecyclerViewClickListener listener){
this.listener = listener;
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public SimpleViewHolder(View itemView, final RecyclerViewClickListener listener) {
super(itemView);
// find view ids here
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener != null)
listener.onRowClicked(getAdapterPosition());
}
});
someViewholderView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener != null)
listener.onViewClicked(v, getAdapterPosition());
}
});
}
}
}
Implement the interface in your Activity / Fragment:
public class YourFragment extends Fragment implements RecyclerViewClickListener {
@Override
public void onViewClicked(View v, int position) {
if(v.getId == R.id.yourDesiredView){
// Do your stuff here
}
}
@Override
public void onRowClicked(int position) {
// Clicked entire row
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With