Adding a colored background with text/icon under swiped row when using Android's RecyclerView

前端 未结 7 594
遥遥无期
遥遥无期 2020-12-02 07:37

EDIT: The real problem was that my LinearLayout was wrapped in another layout, which caused the incorrect behavior. The accepted answer by Sanvywell has

7条回答
  •  广开言路
    2020-12-02 07:50

    In order to implement I used the sample code created by Marcin Kitowicz here.

    Benefits of this solution:

    1. Uses background view with layout bounds instead of creating a Rectangle which will show on top of any Bitmap or Drawable.
    2. Uses Drawable image opposed to Bitmap which is easier to implement than needing to convert a Drawable into a Bitmap.

    The original implementation code can be found here. In order to implement left swipe I used the inverse left and right positioning logic.

    override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
    if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
        var icon = ContextCompat.getDrawable(context!!, R.drawable.ic_save_24dp)
        var iconLeft = 0
        var iconRight = 0
    
        val background: ColorDrawable
        val itemView = viewHolder.itemView
        val margin = convertDpToPx(32)
        val iconWidth = icon!!.intrinsicWidth
        val iconHeight = icon.intrinsicHeight
        val cellHeight = itemView.bottom - itemView.top
        val iconTop = itemView.top + (cellHeight - iconHeight) / 2
        val iconBottom = iconTop + iconHeight
    
        // Right swipe.
        if (dX > 0) {
            icon = ContextCompat.getDrawable(context!!, R.drawable.ic_save_24dp)
            background = ColorDrawable(Color.RED)
            background.setBounds(0, itemView.getTop(), (itemView.getLeft() + dX).toInt(), itemView.getBottom())
            iconLeft = margin
            iconRight = margin + iconWidth
        } /*Left swipe.*/ else {
            icon = ContextCompat.getDrawable(context!!, R.drawable.ic_save_24dp)
            background = ColorDrawable(Color.BLUE)
            background.setBounds((itemView.right - dX).toInt(), itemView.getTop(), 0, itemView.getBottom())
            iconLeft = itemView.right - margin - iconWidth
            iconRight = itemView.right - margin
        }
        background.draw(c)
        icon?.setBounds(iconLeft, iconTop, iconRight, iconBottom)
        icon?.draw(c)
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
    }
    }
    

提交回复
热议问题