Android OnGestureListener 判断手势上下滑动

Android中监听触摸事件一般情况下都是使用OnTouchListener, 但如果要使用一些复杂的手势识别就很麻烦了,不过官方又给我们提供了另外一个借口 OnGestureListener,它可以说是对OnTouchListener的一种封装,可以识别长按,滑动,等等一系列操作。

这里是识别的上下滑动的操作。


布局文件




    


Activity代码

package com.example.testviewpager;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public class TouchActivity extends Activity implements OnGestureListener, OnTouchListener{
	
	private static final int FLING_MIN_DISTANCE = 50;   
	private static final int FLING_MIN_VELOCITY = 0;   
	GestureDetector mGestureDetector = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item);
		View view = findViewById(R.id.layout);
		mGestureDetector = new GestureDetector(this);
		view.setOnTouchListener(this);
		//下面这几行一定要加上否则就只能识别onDown,onShowPress,和onLongPress
		view.setFocusable(true);   
		view.setClickable(true);   
		view.setLongClickable(true);
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		Log.e("onDown", "onDown");
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		Log.e("onShowPress", "onShowPress");
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e){
		// TODO Auto-generated method stub
		Log.e("onSingleTapUp", "onSingleTapUp");
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2,
			float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		Log.e("onScroll", "onScroll");
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		Log.e("onLongPress", "onLongPress");
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		
		
		if (e1.getY()-e2.getY() > FLING_MIN_DISTANCE    
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {    
            // Fling left    
            Toast.makeText(this, "向上手势", Toast.LENGTH_SHORT).show();    
        } else if (e2.getY()-e1.getY() > FLING_MIN_DISTANCE    
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {    
            // Fling right    
            Toast.makeText(this, "向下手势", Toast.LENGTH_SHORT).show();    
        }    
		
		Log.e("onFling", "onFling");
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub 
		return mGestureDetector.onTouchEvent(event);
	}

	
	
}


你可能感兴趣的:(android)