Adding Fling Gesture to an image view - Android

前端 未结 8 1177
南方客
南方客 2020-11-27 11:37

Okay I have been referencing the code here: Fling gesture detection on grid layout

but just can not get it to work. In my main activity I have a simple image define

相关标签:
8条回答
  • 2020-11-27 12:21

    Here's the simpliest working version of flinger I can think of. You can actually tie it to any component, not only ImageView.

    public class MyActivity extends Activity {
        private void onCreate() {
            final GestureDetector gdt = new GestureDetector(new GestureListener());
            final ImageView imageView  = (ImageView) findViewById(R.id.image_view);
            imageView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(final View view, final MotionEvent event) {
                    gdt.onTouchEvent(event);
                    return true;
                }
            });
        }               
    
        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
        private class GestureListener extends SimpleOnGestureListener {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    return false; // Right to left
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    return false; // Left to right
                }
    
                if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                    return false; // Bottom to top
                }  else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                    return false; // Top to bottom
                }
                return false;
            }
        }
    }
    

    No activity onClickListener though (if you don't need to catch any onclick actions) It captures not only horizontal, but vertical also (just delete vertical part if you don't need it), and horizontal swipes have priority as you can see. In places where method returns (nad where my comments are) just call your method or whatever :)

    0 讨论(0)
  • 2020-11-27 12:24
    imageView.setOnTouchListener(new View.OnTouchListener() {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return !gestureDetector.onTouchEvent(event);
        }
    });
    
    0 讨论(0)
提交回复
热议问题