Intro

This post is part three of our RecyclerView exercises series and in it, we will show you how to replace the on-click action with a long-press action using an onLongClickListener and an interface. You can check parts one and two.

Exercise

For this exercise we will use the project we created in a previous post, we will just create another branch and work there. In our exercise we have the following scenario: the user is able to long-press on an item in the RecyclerView, and on long-press, we will display a toast message with the name of the item long-pressed. We will be using an onLongClickListener for this action.

First, we will edit the interface in the adapter, to be properly named for the required action:

After that, in our bind function in the adapter, we replace the onClickListener with an onLongClickListener:

The boolean is true if the callback consumed the long click, false otherwise.

Next, we override the interface method in our activity to display the toast message:

And that’s it, we have replaced our onClickListener logic with onLongClickListener.

You can find the whole project here.

 

Spread the love

Leave a Reply

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