识别手势滑动的方向主要是用的 GestureDetector的onFling ,如果想回顾下GestureDetector 可以参考下面的链接地址
问题也比较简单下面给出代码:
-
public
class FlingActivity extends AppCompatActivity {
-
-
private GestureDetector gestureDetector;
-
-
@Override
-
protected void onCreate(@Nullable Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main_layout);
-
-
gestureDetector =
new GestureDetector(FlingActivity.
this,
-
new GestureDetector.SimpleOnGestureListener() {
-
/**
-
* e1: 第一次按下的位置
-
* e2 当手离开屏幕 时的位置
-
* velocityX 沿x 轴的速度
-
* velocityY: 沿Y轴方向的速度
-
* @param e1
-
* @param e2
-
* @param velocityX
-
* @param velocityY
-
* @return
-
*/
-
@Override
-
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
-
float velocityY) {
-
// 手势向上滑动
-
if (e1.getRawY() - e2.getRawY() >
200) {
-
Toast.makeText(FlingActivity.
this,
"手势向上滑动", Toast.LENGTH_SHORT).show();
-
return
true;
-
}
-
// 手势向下滑动
-
if (e2.getRawY() - e1.getRawY() >
200) {
-
Toast.makeText(FlingActivity.
this,
"手势向下滑动", Toast.LENGTH_SHORT).show();
-
return
true;
-
}
-
-
// 手势向右滑动
-
if ((e1.getRawX() - e2.getRawX()) >
200) {
-
Toast.makeText(FlingActivity.
this,
"手势向右滑动", Toast.LENGTH_SHORT).show();
-
return
true;
-
}
-
-
// 手势向左边滑动
-
if ((e2.getRawX() - e1.getRawX()) >
200) {
-
Toast.makeText(FlingActivity.
this,
"手势向左边滑动", Toast.LENGTH_SHORT)
-
.show();
-
return
true;
// 消费掉当前事件 不让当前事件继续向下传递
-
}
-
-
return
super.onFling(e1, e2, velocityX, velocityY);
-
}
-
});
-
}
-
-
@Override
-
public boolean onTouchEvent(MotionEvent event) {
-
return gestureDetector.onTouchEvent(event);
-
}
-
-
}
转载:https://blog.csdn.net/qq_33210042/article/details/108801875
查看评论