Swipe to Reply: Android Recycler View UI

Shain Singh
MindOrks
Published in
2 min readFeb 17, 2019

Gesture control on Recycler item is a great way to interact. Like swipe the Recycler item and perform some task. This article about to implement swipe to reply feature like WhatsApp.

To implement swipe to reply feature on Recycler item

  1. Create a class which implement the ItemTouchHelper.Callback()
  2. Attach the ItemTouchHelper to Recycler view

Step 1: ItemTouchHelper.SimpleCallback

First, let’s create a new class that extends ItemTouchHelper.SimpleCallback and write a constructor which take swipe action listener as a parameter and override all the methods.

//Constructor
class MessageSwipeController(private val context: Context, private val swipeControllerActions: SwipeControllerActions) :
ItemTouchHelper.Callback(){
}
//Register swipe direction
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
return ItemTouchHelper.Callback.makeMovementFlags(0, RIGHT)
}

After overriding all the method register swipe direction in a methodgetMovementFlags by specifying the direction ItemTouchHelper.Callback.makeMovementFlags(0,RIGHT) You can specify left-right both direction also.

Now method onChildDraw perform rendering of reply UI using setBounds and draw method It’s based on translationX calculation.

override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {

if (actionState == ACTION_STATE_SWIPE) {
setTouchListener(recyclerView, viewHolder)
}

if (mView.translationX < convertTodp(130) || dX < this.dX) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
this.dX = dX
startTracking = true
}
currentItemViewHolder = viewHolder
drawReplyButton(c)
}

On right swipe onChildDraw will be called and if X translation move to specific position trigger the swipe action on evet.action == MotionEvent.ACTION_CANCEL || even.action == MotionEvent.ACTION_UP In our case show the reply UI in chat activity.

For more details of drawReplyButton method check out the sample project from link given at the end of the article.

Step 2: Register the ItemTouchHelper class.

val messageSwipeController = MessageSwipeController(this, object : SwipeControllerActions {
override fun showReplyUI(position: Int) {
showQuotedMessage(messageList[position])
}
})

val itemTouchHelper = ItemTouchHelper(messageSwipeController)
itemTouchHelper.attachToRecyclerView(recyclerView)

Check out the below sample project

Hope you like this article. Discuss, share and 👏 it.

Let’s connect on LinkedIn, Twitter

--

--

Shain Singh
MindOrks

Senior Software Engineer-Android | Flutter | Kotlin