Handling click events in RecyclerView



Handling click events in RecyclerView

For my next trick, I will write about onClick()


This is the third in a series of articles which cover the fundamentals of creating and using RecyclerView. If you already have a solid understanding of how to create a RecyclerView, then carry on. Otherwise, consider starting with this post.

When displaying a list of data with RecyclerView, you may want to have a response when an item is clicked. This response could open a new page with more data, present a toast, remove an item, etc. The possibilities are endless but they are all done using onClick().


Defining the click action

Before creating the listener, create a function in the Activity class that performs the action to be done upon click.


Next, update the Adapter’s constructor to take in the onClick() function.


In the Activity class, pass in the newly created function when you initialize the Adapter.


Adding the onClickHandler()

Now that the action is defined, it is time to attach it to the ViewHolder in the Adapter.

Update the ViewHolder to take in onClick() as a parameter.



In the initializer, call setOnClickListener{} on the itemView.



























Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad