RecyclerView Item onClickListener - Android

How to implement click listener for RecyclerView Items

RecyclerView is a great class that you should consider over ListView for building list interfaces. It offers more flexibility and has built-in hooks that make implementing animations and custom layouts much easier compared to ListView

RecyclerViews allow us to handle item taps in a slightly different way. Instead of providing a listener on the RecyclerView itself, the responsibility is handed off to whoever wants to implement the interface for a click listener.

android-recyclerview-onclicklistener

Learn about How to implement RecyclerView using RecyclerView.Adapter

Let's see how to implement OnItemClickListener in RecyclerView.

1. Implement View.OnClickListener in ViewHolder

public class ViewHolder extends RecyclerView.ViewHolder implements 
View.OnClickListener {
       
    @Override
    public void onClick(View v) {
    }
}

2. Create an interface named OnItemClickListener

public interface OnItemClickListener {
    void onItemClick(FeedItem item);
}

3. Add OnItemClickListener to your adapter

private OnItemClickListener onItemClickListener;

public void setOnItemClickListener(OnItemClickListener onItemClickListener){
    this.onItemClickListener = onItemClickListener;
}

4. Pass the item to the onClick

public class ViewHolder extends RecyclerView.ViewHolder implements 
View.OnClickListener {
       
    @Override
    public void onClick(View v) {
        onItemClickListener.onItemClick(feedItem);
    }
}

5. add setOnItemClickListener from the adapter into your class file

In the activity class, let set the click listener to adapter by calling the setOnItemClickListener() method.
adapter.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(FeedItem item) {
         Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_LONG).show();
    }
});


If you're looking to implement recycler view in Kotlin, check out our latest article: RecyclerView with ItemClickListener in Kotlin


Thanks for reading this article. Hope you would have liked it!. Please share and subscribe to this blog to support. 


Pragnesh Ghoda

A forward-thinking developer offering more than 8 years of experience building, integrating, and supporting android applications for mobile and tablet devices on the Android platform. Talks about #kotlin and #android

Post a Comment

Please let us know about any concerns or query.

Previous Post Next Post

Contact Form