如何通过具有弹跳效果的滑动删除回收站视图中的项目

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

我知道用 ItemTouchHelper.SimpleCallback 滑动即可删除回收站视图项目。但是我想增加更多的功能。

  1. 如果用户将项目向左拉超过一定距离,项目将被删除。
  2. 如果用户没有向左拉超过一定距离,项目将停止,直到右侧的 'delete' 按钮

如何测量用户拉动的距离?? onChildDraw() 方法让我很困惑。 这个我试过了。

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)
}

您应该添加 View.OnTouchListener。像这样:

    // 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;
        }
    });