I have a to do list app and I have created a snackbar that shows up when a user swipes to delete an item. What I want to do is have the undo snackbar reinsert the item that was just deleted.
Here's my code that handles the swipe to delete and show snackbar
override fun onViewSwiped(position: Int) {
deleteTask(list[position].ID)
list.removeAt(position)
notifyItemRemoved(position)
updateNotesPositionInDb()
val snackbar = Snackbar.make((context as Activity).findViewById(R.id.mainLayout), "task deleted", Snackbar.LENGTH_SHORT)
snackbar.setAction("Undo") {
}
snackbar.show()
Keep in mind that this code is used in an Adapter class.
CodePudding user response:
You can save the deleted item and add it back to the list with undo:
The problem is that you already deleted the task in your database, so I think that you should give that deleteTask some delay and only delete the task if the undo is not clicked during that delay.
override fun onViewSwiped(position: Int) {
val list = mutableListOf<String>()
deleteTask(list[position].ID)
val removedItem = list.removeAt(position)
notifyItemRemoved(position)
updateNotesPositionInDb()
val snackbar = Snackbar.make(
(context as Activity).findViewById(R.id.mainLayout),
"task deleted",
Snackbar.LENGTH_SHORT
)
snackbar.setAction("Undo") {
undoDeleteTask(removedItem.ID)
list.add(position, removedItem)
notifyItemInserted(position)
}
snackbar.show()
}