RecyclerView - Where should I handle click events?

Prior to introducing RecyclerView (and its required ViewHolder template), I usually delegated any click events to the corresponding Activity / Fragment using setOnItemClickListener() . (Because I basically see Activity / Fragment as an “controller” object when developing for Android, so any kind of change of view should be made in it.)

Now, since RecyclerView doesn’t really apply to its children in the same way, and that the setOnItemClickListener() (or similar) methods no longer execute for it - where should I handle the click events that may take place? I don’t know ... but processing them in Adapter seems to me inconvenient.

How should we do this?

Thanks in advance!

+8
android android-adapter android-adapterview
source share
2 answers

Create your own viewHolder to view the recycler, as we always do, and in the onBindView method, set the click viewer in the view you want to execute.

 @Override public void onBindViewHolder(final ViewHolder viewHolder, int position) { viewHolder.mRelContent.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // perform ur click here } }); } 
+4
source share

See Jacob's implementation of RecyclerView.OnItemTouchListener . I think this is the best solution.

Hope this helps you. Best wishes.

+3
source share

All Articles