How to implement long press action on RecyclerView items using interface
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:
interface OnLongCLickListener { fun onItemLongClickListener(item: Item, position: Int) }
1
2
3
interface OnLongCLickListener {
fun onItemLongClickListener(item: Item, position: Int)
}
After that, in our bind function in the adapter, we replace the onClickListener with an onLongClickListener:
container.setOnLongClickListener { onLongClickListener.onItemLongClickListener(item, position) true }
1
2
3
4
container.setOnLongClickListener {
onLongClickListener.onItemLongClickListener(item, position)
true
}
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:
override fun onItemLongClickListener(item: Item, position: Int) { Toast.makeText(this, "${item.itemName} long clicked", Toast.LENGTH_SHORT).show() }
1
2
3
override fun onItemLongClickListener(item: Item, position: Int) {
Toast.makeText(this, "${item.itemName} long clicked", Toast.LENGTH_SHORT).show()
}
And that’s it, we have replaced our onClickListener logic with onLongClickListener.
You can find the whole project here.




Comments