我在Android中使用了一个viewpager,并想控制用户可以刷哪个页面。
我正在使用此代码来检测滑动的方向:
// Detects the direction of swipe. Right or left.
// Returns true if swipe is in right direction
public boolean detectSwipeToRight(MotionEvent event){
int initialXValue = 0; // as we have to detect swipe to right
final int SWIPE_THRESHOLD = 100; // detect swipe
boolean result = false;
try {
float diffX = event.getX() - initialXValue;
if (Math.abs(diffX) > SWIPE_THRESHOLD ) {
if (diffX > 0) {
// swipe from left to right detected ie.SwipeRight
result = false;
} else {
Log.e("swipeToLeft", "swipeToLeft");
result = true;
}
}
}
catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
但此代码始终返回“false”。必须在代码中进行哪些更改才能使其正常工作?
答案 0 :(得分:1)
考虑到你总是将起点初始化为0
,你的代码总是返回false似乎是正确的int initialXValue = 0;
我认为您必须检测滑动动作的起点,而不仅仅是管理指向结束点的事件。
你必须考虑两个不同的变量。
int downX; //initialized at the start of the swipe action
int upX; //initialized at the end of the swipe action
buttonIcons.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(final View v, final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
return true;
case MotionEvent.ACTION_UP:
upX = event.getX();
final float deltaX = downX - upX;
if (deltaX > 0 && deltaX > SWIPE_MIN_DISTANCE) {
//DETECTED SWIPE TO RIGHT
}
if (deltaX < 0 && -deltaX > SWIPE_MIN_DISTANCE) {
//DETECTED SWIPE TO LEFT
}
return true;
}
return false;
}
});
}