Android OnTouch向上/向下滑动方向更改 [英] Android OnTouch swipe up/down direction change
本文介绍了Android OnTouch向上/向下滑动方向更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图检测用户仍在屏幕上滑动时何时改变了滑动方向.
I'm trying to detect when an swipe direction was changed while the user still swipes on the screen.
我有类似以下内容(非常基本)来检测滑动方向:
I have something like this (very basic) for detecting the swipe direction:
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN: {
Log.d(TAG, "onTouch: DOWN _Y = " + motionEvent.getRawY());
mLastTouchY = mPrevTouchY = motionEvent.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
Log.d(TAG, "onTouch: MOVE _Y = " + motionEvent.getRawY());
final float dy = motionEvent.getRawY();
if (dy >= mLastTouchY) {
/* Move down */
} else {
/* Move up */
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_UP: {
Log.d(TAG, "onTouch: UP _Y = " + motionEvent.getRawY());
// snap page
break;
}
}
return true;
}
我需要的是实际检测用户何时更改了滑动方向. 例如,上面的代码无法检测到某些边缘情况:
What I need is to actually detect when the user changed the direction of the swipe. For example, the code above fails to detect some edge cases:
- 从Y = 100开始,
- 向下移动到150,
- 前进到50,
- 再次下移直到90
这将被检测为向上滑动,因为初始Y高于最后一个Y
推荐答案
是否要检测滑动的方向变化,有一种简单的方法:
Should you want to detect the direction change of the swipe there is a simple way:
private GestureDetector gestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
findViewById(R.id.myView).setOnTouchListener(this);
gestureDetector = new GestureDetector(this, this);
}
您可以像这样实现OnTouch和GestureListener:
And you implement OnTouch and GestureListeners like this:
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (distanceY > 0){
// you are going up
} else {
// you are going down
}
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
//the rest of the methods you must implement...
这篇关于Android OnTouch向上/向下滑动方向更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文