我使用下面的代码来检测listview上的滑动:
SwipeGestureListener.java
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;
public class SwipeGestureListener implements GestureDetector.OnGestureListener{
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;
protected MotionEvent mLastOnDownEvent = null;
private static final int SWIPE_THRESHOLD_VELOCITY = 100;
public SwipeGestureListener(Context context) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
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(context, "Right Swipe", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(context, "Left Swipe", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
MyActivity.java
ListView listview = (ListView)findViewById(R.id.song_list_listview);
final GestureDetector gdt = new GestureDetector(this, new SwipeGestureListener(this));
listview.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
gdt.onTouchEvent(event);
// TODO Auto-generated method stub
return false;
}
});
此代码有效,但似乎只有在我在列表视图的同一项目上执行滑动手势时才有效。
例如,我有项目1,2和3.当我开始在项目2上滑动时,正在进行的滑动手势必须在项目2布局内,并在项目2布局上结束,以使手势检测起作用。
在listview上检测滑动的最佳方法是什么?谢谢!