GestureActivity.javajava
public class GestureActivity extends Activity {
private GestureDetector gestureDetector;
private Screen screen;ide
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(this,onGestureListener);
//獲得屏幕的大小
screen = GestureUtils.getScreenPix(this);
}this
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
GestureDetector.OnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener(){ci
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float x = e2.getX() - e1.getX();
float y = e2.getY() - e1.getY();
//限制必須得劃過屏幕的1/3才能算劃過
float x_limit = screen.widthPixels / 3;
float y_limit = screen.heightPixels / 3;
float x_abs = Math.abs(x);
float y_abs = Math.abs(y);
if(x_abs >= y_abs){
//gesture left or right
if(x > x_limit || x < -x_limit){
if(x>0){
//right
show("right");
}else if(x
//left
show("left");
}
}
}else{
//gesture down or up
if(y > y_limit || y < -y_limit){
if(y>0){
//down
show("down");
}else if(y
//up
show("up");
}
}
}
return true;
}
};
private void show(String value){
Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
}get
}it
GestureUtils.javaio
public class GestureUtils {event
//獲取屏幕的大小
public static Screen getScreenPix(Context context) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return new Screen(dm.widthPixels,dm.heightPixels);
}
public static class Screen{
public int widthPixels;
public int heightPixels;
public Screen(){
}
public Screen(int widthPixels,int heightPixels){
this.widthPixels=widthPixels;
this.heightPixels=heightPixels;
}ast
@Override
public String toString() {
return "("+widthPixels+","+heightPixels+")";
}
}
}class