I want to set up an onClickListener within my RecyclerView adapter so I can easily refer to the other views to retrieve their tags.
Is it possible to set up an onClickListener in a RecyclerView adapter? How would I do it? Would it affect performance?
Here is my RecyclerView adapter:
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
private Context context;
private List<Post> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public LinearLayout mainLayout;
public TextView username;
public ImageView image;
public ViewHolder(LinearLayout view) {
super(view);
view.setOnCreateContextMenuListener(this);
mainLayout = (LinearLayout) view.findViewById(R.id.main_view);
username = (TextView) view.findViewById(R.id.username);
image = (ImageView) view.findViewById(R.id.image);
}
}
public PostRecyclerAdapter(Context context, List<Post> myDataset) {
this.context = context;
this.mDataset = myDataset;
}
@Override
public PostRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_layout, parent, false);
ViewHolder vh = new ViewHolder((LinearLayout) view);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post postItem = mDataset.get(position);
holder.username.setText(postItem.getUserame());
}
@Override
public int getItemCount() {
return mDataset.size();
}
}
I would like to suggest a much simpler approach than the one given above. in your adapter you would have written static view holder class right for that add the following code
by doing so you can handle individual click of your layout as well as the entire layout click
This is simplest implementation but this will be inside recyclerviews adapter. If you want to get row item clicklistener in activity then use Interface.
You can use GestureDetector for this. This is very simple to use :
Create A class RecyclerTouchListener :
and you can use this class as follow :
Note : Concept is taken from LINK