有人可以帮我解决下面的代码。我正在使用此代码检测屏幕上的手指滑动。
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class ActivitySwipeDetector implements View.OnTouchListener {
private Activity activity;
static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;
public ActivitySwipeDetector(final Activity activity) {
this.activity = activity;
}
public void onRightToLeftSwipe() {
}
public void onLeftToRightSwipe(){
}
public void onTopToBottomSwipe(){
}
public void onBottomToTopSwipe(){
}
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
Log.i("msg", "in MotionEvent.ACTION_DOWN "+event.getX());
downX = event.getX();
downY = event.getY();
}
case MotionEvent.ACTION_UP: {
Log.i("msg", "in MotionEvent.ACTION_UP "+event.getX());
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
// swipe horizontal?
if(Math.abs(deltaX) > MIN_DISTANCE){
// left or right
if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
} else { Log.i("msg", "X-axis Swipe was only " + downX+"-"+upX + " long, need at least " +
MIN_DISTANCE); }
// swipe vertical?
if(Math.abs(deltaY) > MIN_DISTANCE){
// top or down
if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
} else { Log.i("msg", "Y-axis Swipe was only " + downY+"-"+upY + " long, need at least " +
MIN_DISTANCE); }
// return true;
}
}
return false;
}
}
这就是我在我的代码中使用这个类的方法
myTextView.setOnTouchListener(new ActivitySwipeDetector(this) {
public void onRightToLeftSwipe() {
//do some stuff;
}
public void onLeftToRightSwipe() {
//do some stuff;
}
public void onTopToBottomSwipe() {
//do some stuff;
}
public void onBottomToTopSwipe() {
//do some stuff;
}
});
当我测试此代码时(直接在手机上,而不是在模拟器上),upX ad downX变量都返回相同的值。 upY和downY值的情况也是如此。因此,首先不会调用onLeftToRightSwipe()等方法。
答案 0 :(得分:0)
在你的switch语句中,你需要在每个案例的末尾添加一个break;
。
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
Log.i("msg", "in MotionEvent.ACTION_DOWN "+event.getX());
downX = event.getX();
downY = event.getY();
break;
}
case...
答案 1 :(得分:0)
添加一行“return true;”如果MotionEvent.ACTION_DOWN解决了这个问题。