1

I am trying to implement a partial swipe in RecyclerView and add a delete button. I would like to delete the swiped row only after the user clicks the delete button. I am using ItemTouchHelper. SimpleCallback and was able to achieve the partial swipe with the code below. I have two pending tasks:

  1. I am implementing partial swipe using the onChildDraw method. I am currently drawing a red rectangle on partial swipe. I would want to add the text "Delete" inside it. Is it possible to add a Button instead of drawing a rectangle?
  2. How do I add the click listener on the rectange/button to perform the delete action.

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        try {
    
            Bitmap icon;
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                View itemView = viewHolder.itemView;
    
                float height = (float) itemView.getBottom() - (float) itemView.getTop();
                float width = height / 5;
                viewHolder.itemView.setTranslationX(dX / 5);
    
    
                Paint paint = new Paint();
    
                paint.setColor(Color.parseColor("#D32F2F"));
                RectF background = new RectF((float) itemView.getRight() + dX / 5, (float) itemView.getTop(), (float) itemView.getRight(), (float) itemView.getBottom());
    
               RectF icon_dest = new RectF((float) (itemView.getRight() + dX /7), (float) itemView.getTop()+width, (float) itemView.getRight()+dX/20, (float) itemView.getBottom()-width);
    
               c.drawBitmap(null, null, icon_dest, paint);
            } else {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
Saurabh
  • 434
  • 1
  • 4
  • 12
sony
  • 1,557
  • 10
  • 36
  • 50

1 Answers1

1

To answer your questions:

  1. Yes. It's possible, but not in onChildDraw method. There are a lot 3rd party libraries use a two-layer approach. The first layer is your item view, the second has all the buttons. When you swipe, it reveals the button layer, and you can handle click event by setting buttons' OnClickListener.
  2. To add OnClickListener to the buttons you drawn in onChildDraw method, you will have to set recylerView.setOnTouchListener to get (x,y) on screen. Please check AdamWei's post here for instruction.

You can also check my post here. I have implemented the desired effect by using ItemTouchHelper.SimpleCallback. It's a simple helper class, easy to use.

Wenxi Zeng
  • 1,543
  • 1
  • 9
  • 13
  • Please avoid links as they might be broken in the future. This would be acceptable on Quora but not on SO. Please explain how to solve this issue in your answer. – Joaquim Ley Feb 17 '21 at 15:32