Android LazyVerticalGrid 不支持原生的滑动删除,但是可以通过自定义实现。
首先,需要在 LazyVerticalGrid Adapter 中实现一个回调接口,用于在滑动删除时更新数据:
interface OnItemRemovedListener {
fun onItemRemoved(position: Int)
}
然后,在 LazyVerticalGrid Adapter 中实现 ItemTouchHelper 接口以便处理滑动删除事件:
class GridAdapter(val onItemRemovedListener: OnItemRemovedListener) :
RecyclerView.Adapter(), ItemTouchHelperCallback {
// ...
override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
// not used in LazyVerticalGrid
return false
}
override fun onItemDismiss(position: Int) {
onItemRemovedListener.onItemRemoved(position)
notifyItemRemoved(position)
}
// ...
}
在 Activity 或 Fragment 中,构造 ItemTouchHelper 并为 LazyVerticalGrid 设置 TouchHelper:
val itemTouchHelper = ItemTouchHelper(GridAdapter(lazyVerticalGridAdapter))
itemTouchHelper.attachToRecyclerView(lazyVerticalGrid)
lazyVerticalGridAdapter.setOnItemRemovedListener(object : OnItemRemovedListener {
override fun onItemRemoved(position: Int) {
// remove item from data source
dataItems.removeAt(position)
}
})
然后,在 LazyVerticalGrid 中添加 OnItemTouchListener 处理滑动删除事件:
lazyVerticalGrid.apply {
addOnItemTouchListener(object : OnItemTouchListener {
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
// get the touched view
val childView = rv.findChildViewUnder(e.x, e.y)
if (childView != null && gestureDetector.onTouchEvent(e)) {
// handle delete event with itemTouchHelper
itemTouchHelper.startSwipe(this@apply.getChildViewHolder(childView))
return true
}
return false
}
// ...
})
}