Android ListView Swipe Right and Left to Accept and Reject

前端 未结 6 1175
遥遥无期
遥遥无期 2020-12-05 11:37

I want to develop a list view that when swiped left to right - displays in the left corner an accept (true) icon (non clickable - show just a color change when swiping left

6条回答
  •  甜味超标
    2020-12-05 12:05

    It worked for me... I hope it will work for you..!

    set OnTouchListener to listview as

    listview.setOnTouchListener(new OnSwipeTouchListener(getActivity(),
                listview));
    

    The OnSwipeTouchListener class is as follows:

    public class OnSwipeTouchListener implements OnTouchListener {
    
        ListView list;
        private GestureDetector gestureDetector;
        private Context context;
    
        public OnSwipeTouchListener(Context ctx, ListView list) {
            gestureDetector = new GestureDetector(ctx, new GestureListener());
            context = ctx;
            this.list = list;
        }
    
        public OnSwipeTouchListener() {
            super();
        }
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    
        public void onSwipeRight(int pos) {
            //Do what you want after swiping left to right
    
        }
    
        public void onSwipeLeft(int pos) {
    
            //Do what you want after swiping right to left
        }
    
        private final class GestureListener extends SimpleOnGestureListener {
    
            private static final int SWIPE_THRESHOLD = 100;
            private static final int SWIPE_VELOCITY_THRESHOLD = 100;
    
            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
    
            private int getPostion(MotionEvent e1) {
                return list.pointToPosition((int) e1.getX(), (int) e1.getY());
            }
    
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2,
                    float velocityX, float velocityY) {
                float distanceX = e2.getX() - e1.getX();
                float distanceY = e2.getY() - e1.getY();
                if (Math.abs(distanceX) > Math.abs(distanceY)
                        && Math.abs(distanceX) > SWIPE_THRESHOLD
                        && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (distanceX > 0)
                        onSwipeRight(getPostion(e1));
                    else
                        onSwipeLeft(getPostion(e1));
                    return true;
                }
                return false;
            }
    
        }
    }
    

提交回复
热议问题