Issue
I have a recyclerview which has a swipeToDeleteHandler:
private fun swipeToDeleteHandler() {
simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(
0,
ItemTouchHelper.LEFT
) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
Toast.makeText(this@MainActivity, "on Move", Toast.LENGTH_SHORT).show()
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
Toast.makeText(this@MainActivity, "Removed! ", Toast.LENGTH_SHORT).show()
//Remove swiped item from list and notify the RecyclerView
deleteRowFromDb(viewHolder.adapterPosition + 1)
//adapter.notifyItemChanged(viewHolder.adapterPosition)
}
}
}
Which deletes from my SQLi db the row that the user swiped. The problem is, what is the most efficient way to add a red background with an trash icon while the user is swiping to delete the row? It is seen in most apps nowadays.
Solution
If all you need to do its just delete element on swipe the easiest way is to draw it on ItemTouchHelper.SimpleCallback
override fun onChildDraw(canvas, recyclerView, viewHolder, ..) {
val itemView = viewHolder.itemView
val itemHeight = itemView.bottom - itemView.top
// Draw the red delete background
background.color = backgroundColor
background.setBounds(
itemView.right + dX.toInt(),
itemView.top,
itemView.right,
itemView.bottom
)
background.draw(canvas)
// Calculate position of delete icon
val iconTop = itemView.top + (itemHeight - inHeight) / 2
val iconMargin = (itemHeight - inHeight) / 2
val iconLeft = itemView.right - iconMargin - inWidth
val iconRight = itemView.right - iconMargin
val iconBottom = iconTop + inHeight
// Draw the delete icon
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
icon.draw(canvas)
super.onChildDraw(canvas, recyclerView, viewHolder, ...)
}
But if you need more than just remove item on swipe, for example, you need two buttons like "Delete" and "Edit" you can use 3rd party libraries like This One
Answered By - Alexandr Ukolov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.