您的位置:首页 > 移动开发 > Android开发

Android 手势识别进行屏幕切换

2015-02-02 20:41 369 查看
在需要的Activity中定义出手势

private GestureDetector mGestureDetector;//定义出手势
然后实例化它:

mGestureDetector = new GestureDetector(result.this, new gesturedetector(result.this, MainActivity.class));
new gestureddetector这个类是自定义的一个继承了SimpleOnGestureListener的类

gestureddetector类如下:

public class gesturedetector extends SimpleOnGestureListener {
private Context context1;
private Class<?> clazz;

public gesturedetector(Context context1, Class<?> clazz) {
this.context1 = context1;
this.clazz = clazz;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {//e1代表手指刚接触到屏幕的点,e2代表手指离开屏幕的点,后面两个分别代表速度
//判断一下操作的正确性
if(Math.abs(e1.getRawY()-e2.getRawY())>100){
Toast.makeText(context1,"操作错误", 0).show();
return true;
}
if (e1.getRawX() - e2.getRawX() > 200) {
// 第一次触摸的x减去离开里的x大于200,向下换
Intent in = new Intent(context1, clazz);
context1.startActivity(in);
((Activity) context1).finish();
overridePendingTransition(R.anim.tran_next_in, R.anim.tran_next_out);

return true;
}
if (e2.getRawX() - e1.getRawX() > 200) {
// 返回去
Intent inn = new Intent();
inn.setClass(context1, clazz);
context1.startActivity(inn);
((Activity) context1).finish();
//overridePendingTransition(R.anim.tran_next_out, R.anim.tran_next_in);
return true;
}

return super.onFling(e1, e2, velocityX, velocityY);
}

}


最后复写这个Activity的onTouchEvent 方法就好

@Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}


大功告成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐