欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android--监听左右滑动事件

程序员文章站 2024-03-24 17:49:46
...

主要思路:activity实现OnTouchListener接口,继承方法,GestureDetector.SimpleOnGestureListener的一个对象,用来识别各种手势动作,源码中SimpleOnGestureListener实现的是OnGestureListener, OnDoubleTapListener这两个接口,如果你只是做检测左右滑动可以去只实现OnGestureListener,然后覆盖public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)方法。

public class fgMeterActivity extends Activity implements View.OnTouchListener{
	private static final int FLING_MIN_DISTANCE = 50;
    private static final int FLING_MIN_VELOCITY = 0;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meter);

        ButterKnife.bind(this);

        mGestureDetector = new GestureDetector(this, myGestureListener);
        ScrollView scrollView = findViewById(R.id.sc);//布局的主容器
        scrollView.setOnTouchListener(this);
        scrollView.setLongClickable(true);//必需设置这为true 否则也监听不到手势
    }
	
	@Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        return mGestureDetector.onTouchEvent(event);
    }
	
	GestureDetector.SimpleOnGestureListener myGestureListener = new GestureDetector.SimpleOnGestureListener(){
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            Log.e(TAG, "开始滑动");
            float x = e1.getX()-e2.getX();
            float x2 = e2.getX()-e1.getX();
            if(x > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY){
                Log.i(TAG,"向左手势");

            }else if(x2 > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY){
                Log.i(TAG,"向右手势");

            }

            return false;
        };
    };
}