好的,这件事情差点把我逼疯了。
几天前,我实现了下面的代码,并成功地调用了toast,当我尝试向右或向左滑动时。
然而,现在它不能被调用,因为e1始终为空!
怎么会发生这种情况?我在模拟器上尝试了这个代码,但是有用户报告说,在真实设备上也无法使用。
public class SwipeGestureListener extends GestureDetector.SimpleOnGestureListener{
private static final int SWIPE_MIN_DISTANCE = 150;
private static final int SWIPE_MAX_OFF_PATH = 100;
private static final int SWIPE_THRESHOLD_VELOCITY = 100;
private final Activity activity;
protected MotionEvent mLastOnDownEvent = null;
public SwipeGestureListener(Activity activity) {
this.activity = activity;
}
@Override
public boolean onDown(MotionEvent e) {
mLastOnDownEvent = e;
System.out.println(e);
return super.onDown(e);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
System.out.println(e1 + " " + e2);
if (e1==null)
e1 = mLastOnDownEvent;
if (e1==null || e2==null)
return false;
float dX = e2.getX()-e1.getX();
float dY = e2.getY()-e1.getY();
if (Math.abs(dY)<SWIPE_MAX_OFF_PATH && Math.abs(velocityX)>=SWIPE_THRESHOLD_VELOCITY && Math.abs(dX)>=SWIPE_MIN_DISTANCE ) {
if (dX>0) {
Toast.makeText(activity.getApplicationContext(), "Right Swipe", Toast.LENGTH_SHORT).show();
activity.fetchPrevious();
} else {
Toast.makeText(activity.getApplicationContext(), "Left Swipe", Toast.LENGTH_SHORT).show();
activity.fetchNext();
}
return true;
}
return false;
}
}
实现手势的代码:
final GestureDetector gdt = new GestureDetector(this, new SwipeGestureListener(this));
listview.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
gdt.onTouchEvent(event);
return false;
}
});