android开发笔记之activity 左右滑动的实现

这是一个在activity中左右滑动的实现样例:

在activity中:

origin code:

1.包文件:

//hongyu hexiaoming mms 20131225 start
import android.util.Log;

import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;

//hongyu hexiaoming mms 20131225 end

2.定义变量:

//hongyu hexiaoming mms 20131225 start	

private static final int FLING_MIN_DISTANCE = 120;
private static final int FLING_MIN_VELOCITY = 200;


    
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;

private SimpleOnGestureListener mySimpleOnGestureListener = new SimpleOnGestureListener(){

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) {
	// TODO Auto-generated method stub
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {				
		showNextMessage();									
		}	
		if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {	   			
			showPreMessage();  			
		}					
			return false;			
		}
};


3.在onCreate方法中:

//hongyu hexiaoming mms 20131225 start	
gestureDetector = new GestureDetector(mySimpleOnGestureListener);
				
gestureListener = new View.OnTouchListener() {
	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		if (gestureDetector.onTouchEvent(arg1)) {
			return true;
		}
			return false;
		}
};

//hongyu hexiaoming mms 20131225 end




4.dispatchTouchEvent方法:

 @Override
public boolean dispatchTouchEvent(MotionEvent event) {

	  if (gestureDetector.onTouchEvent(event)) {
	   event.setAction(MotionEvent.ACTION_CANCEL);
	  }
	  return super.dispatchTouchEvent(event);

}	



参考资料:

(1)http://blog.csdn.net/c_see/article/details/6457447

android 手势左右滑动

(2)http://blog.csdn.net/zzy916853616/article/details/6525648

android开发之滑动手势翻图 滑动手势监听

你可能感兴趣的:(android,gesturedetector,gestureListener)