1

有人可以帮我写下面的代码。我正在使用此代码来检测屏幕上的手指滑动。

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 和 downX 变量都返回相同的值。upY 和 downY 值也是如此。因此,方法 onLeftToRightSwipe() 等一开始就没有被调用。

4

2 回答 2

0

在您的 switch 语句中,您需要break;在每个 case 的末尾添加 a。

switch(event.getAction()){

    case MotionEvent.ACTION_DOWN: {
        Log.i("msg", "in MotionEvent.ACTION_DOWN "+event.getX());
        downX = event.getX();
        downY = event.getY();
        break;
        }
    case...
于 2013-02-27T19:51:47.037 回答
0

添加一行“return true;” 如果 MotionEvent.ACTION_DOWN 解决了​​问题。

于 2013-02-27T21:31:26.437 回答