相信大家在做OnGestureListener滑动切换窗口的时候,会遇到这样的问题。就是当界面中含有listview的时候,OnGestureListener的左右触屏滑动就被listview自己吃掉了。
翻看api帮助文档和自己的一些理解,决定从对listview重写开始,开解决这个头疼的问题。
以下是本人对ListView类的重写:
class GestureListView extends ListView {
public GestureListView(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(mLvDetector.onTouchEvent(ev)) return true;
return super.onTouchEvent(ev);
}
private GestureDetector mLvDetector = new GestureDetector(new OnGestureListener() {
//手指在屏幕上移动距离小于此值不会被认为是手势
private static final int SWIPE_MIN_DISTANCE = 120;
//手指在屏幕上移动速度小于此值不会被认为手势
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDown(MotionEvent e) {
int position = pointToPosition((int)e.getX(), (int)e.getY());
if( position != ListView.INVALID_POSITION) {
View child = getChildAt(position - getFirstVisiblePosition());
if(child != null) child.setPressed(true);
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//left
Log.i("GestureDemo", "ListView left");
mVf.showNext();
return true;
}else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//right
Log.i("GestureDemo", "ListView right");
mVf.showPrevious();
return true;
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
System.out.println("Listview long press");
int position = pointToPosition((int)e.getX(), (int)e.getY());
if( position != ListView.INVALID_POSITION) {
View child = getChildAt(position - getFirstVisiblePosition());
if(child != null) GestureListView.this.showContextMenuForChild(child);
}
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
});
}