Android - RecyclerView: Implementing single item click and long press (Part-II)


This article is a continuation, please read through Implementing ReyclerView

Creating Interface

I hope you have read my previous article. Let me take you from there. Under MainActivity, We need to create a simple interface for single tap and for long press events, by passing “view” and its “position” as parameters

Creating InnerClass

Under MainActivity, Let’s create an inner class implementing RecyclerView.OnItemTouchListener. We also need to make use of ClickListener interface in this inner class. GestureDetector class is used to listen for various touch events. To learn more about GestureDetector, please refer this link

Adding Click Listeners to RecyclerView

Now let’s add the ItemTouchListener to the RecyclerView, where we will pass RecyclerTouchListener class. This will implement onClick and onLongClick methods.These methods will listen for the click and long press events on the particular position of the view.

So….. our Listeners are all ready. Let’s run our project.

Et voila !! Here is our output !

Single click on First Item (position 0)
Long press on the first Item (position 0)

Bonus Information :

Accessing Particular View Component in the RecyclerView Item

In order to access particular view component inside RecyclerView, for example, In order to perform some operation only on clicking the profile image in the RecyclerView row item, then here is the small hack for you.

We can define the component by findViewById via it’s respective View. Here is the code for you.

Now you can perform any operation on clicking the image. Follow the same for the other view components.

Implementing Click Events for Fragment

For beginners, In order to implement the single tap and long press event listeners within a fragment, you need to pass the right context. Using this within fragments, will not allow the fragment to know which activity context you are passing. So solution is to replace this/MainActivity.this with getActivity().

Fork me on GitHub

Check out the complete source code in the following link:

Happy Coding !!

Android Dev at Backbase | #1 Google AAD | Public Speaker | Blogger | Creative Coder & Logical Designer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store