首页 > 解决方案 > 在 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 数据库中删除用户刷过的行。问题是,当用户滑动删除行时,添加带有垃圾桶图标的红色背景的最有效方法是什么?现在在大多数应用程序中都可以看到它。

标签: androidandroid-layoutkotlin

解决方案


如果您只需要在滑动时删除元素,最简单的方法就是在 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 方库


推荐阅读