要做的东西需要判断一下上下左右的滑动,所以就查了一下,发现需要定义一个GestureDetector的变量,然后监听手的动作。
用了两个文件,一个是获取屏幕信息的类ScreenInfo,另外一个就是主类MainActivity了
public class ScreenInfo {
public int widthPixels;
public int heighPixel;
public ScreenInfo(int widthPixels, int heighrPixels) {
this.widthPixels = widthPixels;
this.heighPixel = heighrPixels;
}
public static ScreenInfo getSreenInfo(Context context) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager window = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
window.getDefaultDisplay().getMetrics(dm);
return new ScreenInfo(dm.widthPixels, dm.heightPixels);
}
}
public class MainActivity extends Activity {
public static final int RIGHT = 0;
public static final int LEFT = 1;
public static final int UP = 2;
public static final int DOWN = 3;
private GestureDetector gestureDector;
private ScreenInfo screen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = ScreenInfo.getSreenInfo(this);
gestureDector = new GestureDetector(MainActivity.this, OnGestureListener);
}
private GestureDetector.OnGestureListener OnGestureListener =
new GestureDetector.OnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
return false;
}
@Override
public void onLongPress(MotionEvent arg0) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float arg2,
float arg3) {
float x = e2.getX() - e1.getX();
float y = e2.getY() - e1.getY();
//判断为屏幕宽度的1/4
float x_min = screen.widthPixels / 4;
//判断为屏幕高度的1/5
float y_min = screen.heighPixel / 5;
if (x > x_min || x < -x_min) {
if (x > 0) {
doResult(RIGHT);
} else if (x <= 0) {
doResult(LEFT);
}
}
if (y > y_min || y < -y_min) {
if (y > 0) {
doResult(DOWN);
} else if (y <= 0) {
doResult(UP);
}
}
return true;
}
@Override
public boolean onDown(MotionEvent arg0) {
return false;
}
};
/**
*判断结果为上下左右的哪种情况
*/
public void doResult(int action) {
switch (action) {
case RIGHT:
show("RIGHT");
break;
case LEFT:
show("LEFT");
break;
case UP:
show("UP");
break;
case DOWN:
show("DOWN");
break;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDector.onTouchEvent(event);
}
private void show(String value) {
Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
}
}
只是简单的小Demo,知道是那种手势滑动后就可以进行自己想要做的操作了