To implement such behavior in a RecyclerView, you need to declare an ItemTouchHelper
, like so:
// The class to detect swipes and drags
private lateinit var itemTouchHelper: ItemTouchHelper
The ItemTouchHelper
class has a ItemTouchHelper.SimpleCallback.onChildDraw
callback method, where you can detect if a user swept right or left on an item in your recyclerview. So next, we'll now implement this callback, like so:
private fun setupRecyclerView() {
val myRecyclerView = findViewById<RecyclerView>(R.id.myRecyclerView)
val customAdapter = CustomAdapter()
myRecyclerView.adapter = customAdapter
val simpleCallback = object :
ItemTouchHelper.SimpleCallback(
0,
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean = false
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
// If you want to add a background, a text, an icon
// as the user swipes, this is where to start decorating
// I will link you to a library I created for that below
super.onChildDraw(
c,
recyclerView,
viewHolder,
dX,
dY,
actionState,
isCurrentlyActive
)
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
when (direction) {
ItemTouchHelper.LEFT -> {
// Do something when a user swept left
}
ItemTouchHelper.RIGHT -> {
// Do something when a user swept right
}
}
}
}
itemTouchHelper = ItemTouchHelper(simpleCallback)
itemTouchHelper.attachToRecyclerView(myRecyclerView)
}
Now that swipe behavior will now be listened in your recyclerview.
Also, in case you want a background, icon or text to be shown as the user of your
app swipes, you can use this awesome library I created just for that usage.
you can download it to your project if you're using gradle.
Here's the link to the documentation for it:
https://github.com/kevingermainbusiness/ItemDecorator