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
One thought on “Android Basics – Learn how to handle the user clicks in a RecyclerView”