【发布时间】:2022-11-17 10:07:54
【问题描述】:
我有一个 Snackbar,当用户在 RecyclerView 元素上滑动以删除它时,它正在打开。这个 Snackbar 允许用户撤消他的操作。我知道如何取回 RecyclerView 的元素。但我也有一个数据库(SQLite)。在我看来,从 detabase 中删除的最好方法是在我了解用户不按“撤消”时执行此操作。否则我需要先删除然后再添加。
我想做这样的事情:
when (snackbar_button){
was_pressed -> adapter.restoreItem(cachedPosition, cachedItem)
was_not_pressed -> dbManager.removeItem(listArray[pos].id.toString())
}
这是我在 MainActivity 上的代码:
val onSwipe = object : OnSwipe(this) {
override fun onSwiped(viewHolder: ViewHolder, direction: Int) {
val cachedPosition = viewHolder.absoluteAdapterPosition
val cachedItem = adapter.listArray[cachedPosition]
when (direction) {
ItemTouchHelper.RIGHT -> {
adapter.removeItem(cachedPosition)
Snackbar.make(binding.rv, "Deleted", Snackbar.LENGTH_SHORT)
.apply {
setAction("Undo") {
adapter.restoreItem(cachedPosition, cachedItem)
}
show()
}
}
}
}
}
我的适配器:
fun removeItem(pos: Int) {
listArray.removeAt(pos)
notifyItemRemoved(pos)
}
fun restoreItem(pos: Int, listMain: ListItem) {
listArray.add(pos, listMain)
notifyItemInserted(pos)
}
我在数据库中删除的代码:
fun removeItem(_id: String) {
val id = BaseColumns._ID + "=$_id"
【问题讨论】:
标签: android kotlin android-recyclerview snackbar itemtouchhelper