I was exploring RecyclerView
and I was surprised to see that RecyclerView
does not have onItemClickListener()
. Because RecyclerView
extends
android.view.ViewGroup
and ListView
extends
android.widget.AbsListView
. However I solved my problem by writing onClick
in my RecyclerView.Adapter
:
public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
}
@Override
public void onClick(View v) {
}
}
But still I want to know why Google removed onItemClickListener()
?
Is there a performance issue or something else?
I wrote a library to handle android recycler view item click event. You can find whole tutorial in https://github.com/ChathuraHettiarachchi/RecycleClick
or to handle item long press you can use
recyclerview animation has not been tested, the other is normal. I think it has been optimized to the maximum. Interface has other uses, you can temporarily ignore.
This is Interface
This is an abstract class
You only need it
I like this way and I'm using it
Inside
Put
And create this class anywhere you want it
I've read before that there is a better way but I like this way is easy and not complicated. I hope it'll help you ..!
Guys use this code in Your main activity. Very Efficient Method
Here is your Adapter class.
After this you will get this override method in your activity.
Thanks to @marmor, I updated my answer.
I think it's a good solution to handle the onClick() in the ViewHolder class constructor and pass it to the parent class via OnItemClickListener interface.
MyAdapter.java
Usage of adapter in other classes:
MyFragment.java
Here is a way to implement it quite easily if you have a list of POJOs and want to retrieve one on click from outside the adapter.
In your adapter, create a listener for the click events and a method to set it:
}
In your ViewHolder, implement onClickListener and create a class member to temporarily store the POJO the view is presenting, that way (this is an example, creating a setter would be better):
Back in your adapter, set the current POJO when the ViewHolder is bound (or to null if the current view doesn't have one):
That's it, now you can use it like this from your fragment/activity: