这是我用来接收触摸事件的代码,并将它们输入到我的画布用于翻译的x,y中:
VelocityTracker mVelocity;
Scroller scroller;
@Override
public boolean onTouchEvent(MotionEvent event) { //On touch
super.onTouchEvent(event);
mVelocity = VelocityTracker.obtain();
mVelocity.addMovement(event);
//Log.d("VELOCITY","("+mVelocity.getXVelocity()+","+mVelocity.getYVelocity()+")");
if(event.getActionMasked()==MotionEvent.ACTION_MOVE){ //If it's a drag, call scrollMove
mVelocity.computeCurrentVelocity(1);
scrollMove();
}
if(event.getActionMasked()==MotionEvent.ACTION_UP) { //or scrollFling
mVelocity.computeCurrentVelocity(1);
scrollFling();
}
mVelocity.recycle();
return true;
}
void scrollMove(){ //Canvas is constantly translating by (scrollMove.x,scrollMove.y) every time invalidate() is called
scrollMove.x += mVelocity.getXVelocity() * 10f;
scrollMove.y += mVelocity.getYVelocity() * 10f;
invalidate();
}
void scrollFling(){ //how does scroller.fling work?
scroller.fling(getScrollX(),getScrollY(),(int)-mVelocity.getXVelocity(),(int)-mVelocity.getYVelocity(),0,0,10000,10000);
invalidate();
}
@Override
public void computeScroll() {
super.computeScroll();
if(!scroller.isFinished()){
scroller.computeScrollOffset();
scrollMove.x += scroller.getCurrX();
scrollMove.y += scroller.getCurrY();
//postInvalidateOnAnimation();
postInvalidateOnAnimation(); //Alternated between all 3 of these
postInvalidate(); //??
invalidate(); //??
Log.d("FLING","Should be flinging"); //This is only called once
}
}
因此,滚动正在按我预期的那样工作,但滚动不起作用。在不断调用scroll方法以返回值并转换画布的同时,fling仅被调用一次,并返回我放入函数调用中的任何最大值。
我认为scroller.fling / computeScroll是每帧的递归回调,并且只要未结束,我将收到有关将视图转换到何处的信息。我在做什么错了?
答案 0 :(得分:0)
(感谢irc.freenode / android-dev中的@Roughy)
这里的第一个问题是您将错误的值传递给.fling()
scroller.fling(startX, startY, velX, velY, minX, MAXX, MINY, MAXY);
您翻转了最小值/最大值。
第二个问题是,每次发生移动事件更改时,您都会调用mVelocity = VelocityTracker.obtain();
,这会为每个移动帧创建一个新的速度跟踪器,您应该仅在MotionEvent.ACTION_DOWN
上调用一次,然后分别在ACTION_MOVE和ACTION_UP上调用mVelocity.addMovement(event);
。
也可以在ACTION_UP上致电mVelocity.recycle();
。