您的位置:首页 > 移动开发 > Android开发

Android GestureDetector手势做控件滚动的效果

2016-06-29 18:34 465 查看
最近要做一个自定义的表格的水平滚动,所以用了手势进行滚动,虽然效果不是很好,但是大致的代码就下面.

下面我们要实例化一个手势监听器OnGestureListener然后把我们要做的事放在onFling()方法中进行处理,

四个参数分别是(起始位置,结束位置,水平滑动速度,垂直滑动速度)

不过这种滚动效果对于表格来说就有点反应慢,不过要弄的好点的话,还是可以采用原始方法动态将表格添加到HorizontalScrollView也可以实现此滚动效果

private GestureDetector Gesture = new GestureDetector(context, mOnGesture);

private int moveX = 0;
private int mCurX = 0;
private int screenWidth;
private int screenHeight;

/**
* 分发触摸事件
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
super.dispatchTouchEvent(ev);
return mGesture.onTouchEvent(ev);
}

private int verticalMinistance = 10;    //水平最小识别距离
private int minVelocity = 5;            //最小识别速度

private GestureDetector.OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {

//这里实现监听滚动事件处理
if (e1.getX() - e2.getX() > verticalMinistance && Math.abs(velocityX) > minVelocity) {
moveX = (int) (e1.getX() - e2.getX());
//                Log.e(TAG, "turn left:moveX-->" + moveX);
} else if (e2.getX() - e1.getX() > verticalMinistance && Math.abs(velocityX) > minVelocity) {
moveX = (int) (e1.getX() - e2.getX());
//                Log.e(TAG, "turn right:moveX-->:" + moveX);
}
mCurX += moveX;
if (mCurX < 0) {
if (Math.abs(mCurX) > 0) {
moveX = moveX + Math.abs(mCurX);
} else {
moveX = 0;
}
mCurX = 0;
}

int width = screenWidth - viewWidth + marginLeft;
if (mCurX > width) {
if (mCurX - moveX < width) {
moveX = width - (mCurX - moveX);
} else {
moveX = 0;
}
mCurX = width;
}
Log.e(TAG, "moveX:" + moveX + "; mCurX:" + mCurX);
scrollBy(moveX, 0);
requestLayout();
return false;
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: