Adding click handler for RecyclerView List Entries

If you’re migrating from the ListView to RecyclerView in API Level 21 support library (i.e. Android 5.0 / Lollipop), you may be wondering how to add a click listener for entries in the list. With the ListView you would provide a single listener for all list entries using the ListView.setOnItemClickListener() method, which takes an implementation of the AdapterView.OnItemClickListener interface as its parameter. In your implementation of this interface you would override the onItemClick() method where you are given the ListView instance, the View for the entry in the list, its position, and ID as method parameters.

The stumbling block with the RecyclerView is that it does not have this setOnItemClickListener() method. The solution is actually quite simple, you can use the standard setOnClickListener() method provided by the View object. You can do this for the View objects corresponding to each list entry.

You would typically inflate the required View object from the respective resource definition in your override of the RecyclerView.Adapter.onCreateViewHolder() method. You would also construct your version of the RecyclerView.ViewHolder class there and pass the inflated View object as a constructor parameter.

The View.setOnClickListener() accepts a View.OnClickListener implementation as its parameter, and your ViewHolder is a good place to implement this. This is because the ViewHolder class has access to the list entry View object, its parent, position, and ID which are exactly the same as the parameters you were provided in the old ListView onItemClick() method.

Your ViewHolder class could look something like the following:

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
    protected ViewHolder(View v)
    {
        super(v);
        
        // Inflate all your UI elements for the list entry ..
        
        // and ...
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        int pos = this.getPosition();
        long id = this.getItemId();
        ViewParent parent = v.getParent();
    }
}

And that’s really it! The code above should provide a good start for your ViewHolder class. Hopefully this has been helpful.

Author: Musaul Karim

Software Engineer, Hobbyist Photographer, and a bit of a gadget geek.

Leave a Reply

Your email address will not be published. Required fields are marked *