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

前端 未结 7 570
遥遥无期
遥遥无期 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:54

    I was struggling to implement this feature as well, but you steered me in the right direction.

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            // Get RecyclerView item from the ViewHolder
            View itemView = viewHolder.itemView;
    
            Paint p = new Paint();
            if (dX > 0) {
                /* Set your color for positive displacement */
    
                // Draw Rect with varying right side, equal to displacement dX
                c.drawRect((float) itemView.getLeft(), (float) itemView.getTop(), dX,
                        (float) itemView.getBottom(), p);
            } else {
                /* Set your color for negative displacement */
    
                // Draw Rect with varying left side, equal to the item's right side plus negative displacement dX
                c.drawRect((float) itemView.getRight() + dX, (float) itemView.getTop(),
                        (float) itemView.getRight(), (float) itemView.getBottom(), p);
            }
    
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }
    }
    

提交回复
热议问题