android - 在 RecyclerView 中滑动删除时如何添加具有红色背景颜色的布局
问题描述
我有一个 recyclerview,它有一个 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)
}
}
}
这会从我的 SQLi 数据库中删除用户刷过的行。问题是,当用户滑动删除行时,添加带有垃圾桶图标的红色背景的最有效方法是什么?现在在大多数应用程序中都可以看到它。
解决方案
如果您只需要在滑动时删除元素,最简单的方法就是在 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, ...)
}
但是,如果您需要的不仅仅是在滑动时删除项目,例如,您需要两个按钮,如“删除”和“编辑”,您可以使用像This One这样的 3rd 方库
推荐阅读
- reactjs - 到达路由器未显示匹配 url 的正确组件
- c++ - 基类指针列表,获取函数成员的不同返回值
- reactjs - 带有自定义 React 组件的 styled-components:传递道具
- oracle - 既然 Flash 已达到其 EOL,我该如何运行 Oracle Enterprise Manager?
- assembly - 为什么 E8 F2 FF FF FF 转换为调用 0xFFFFFFF7?
- python - Python 代码在一台计算机上工作,但不是在其他计算机上工作:“预期的 str、字节或 os.PathLike 对象,而不是列表”
- php - Dolibarr 项目模块:DB_ERROR_42803
- spring - 将动态目录添加到 RotatingServerAdvice Spring 集成
- excel - 试图从 Ebay 网站上抓取列表但无法完成
- gitlab - 创建新的合并请求线程时引用的 GitLab line_code 是什么