Search code examples
androidandroid-recyclerviewitemtouchhelper

How to delete item in recycler view through swipe with bounce effect


I know delete recycler view item through swipe with ItemTouchHelper.SimpleCallback immediately. But I want to add more function.

  1. If user pulls left the item over a certain distance, item will be deleted.
  2. If user has not pulled left more than a certain distance, item stops until the 'delete' button on the right

How can I measure the distance the user pulls?? onChildDraw() method makes me confuse. I've tried this.

override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
    var dx = Math.max(dX, -300F)    // -300F is 'delete' button width
    // I thought the item view of recycler view would be farther away from the right wall by the larger of of dX and -300F
    super.onChildDraw(c, recyclerView, viewHolder, dx, dY, actionState, isCurrentlyActive)
}

Solution

  • You should add View.OnTouchListener. Something like this:

        // in the creation of the view holder
        view.setOnTouchListener(new View.OnTouchListener() {
    
            private int downX = 0;
            private int upX = 0;
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:{
                        downX = event.getX();}
                    case MotionEvent.ACTION_UP:{
                        upX = event.getX();
    
                        float deltaX = downX - upX;
    
                        if(deltaX>300F){
                           swipeToLeft();
                           return  true;
                        }
                    }
                }
    
                return false;
            }
        });