Android Basics – Learn how to handle the user clicks in a RecyclerView

You are familiar with how to respond to user clicks in a ListView using an OnItemClickListener. RecyclerView does not have a similar set of built in functionality so you will have to write some code to handle user clicks.

The code you will add will be in the Adapter’s onBindViewHolder. You will also add an interface, similar to the ay you did for Fragment interaction.

Follow the steps below:

Add a Listener interface to the Adapter.

public static interface Listener{
    public void onClick(int position);
}

Add a setListener method. This method will be called from the Activity.

public void setListener(Listener listener) {
    mListener = listener;
}

Add setOnClickListener

cardView.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view){
        if(mListener != null){
            mListener.onClick(position);
        }
    }
});

In Activity class set the Listener defined in Adapter.

SampleAdapter adapter = new SampleAdapter(inputData);
adapter.setListener(new SampleAdapter.Listener() {
    @Override
    public void onClick(int position) {
        //Add code here
    }
});

Source code is available here

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s