我在我的应用程序中添加了一个可通过触摸移动的drawable,并根据手指移动速度执行不同的操作。我检查了事件,发现只能使用MotionEvent.ACTION_MOVE来检测是否有移动。因此,我保存了最后一次移动的时间戳,并获取实际距离,计算移动的增量距离,并使用公式
速度= 距离/时间
然而,速度值显示各种数字,从0到大约6不等,无论我慢慢地或快速地使用手指。我应该修改什么才能获得触摸移动的速度?我使用以下代码:
@Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
final int X = (int) motionEvent.getRawX();
final int Y = (int) motionEvent.getRawY();
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
oldTimeStamp=System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
speed=0;
textView.setText("speed: " + speed);
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
timeStamp= System.currentTimeMillis();
long diff=timeStamp-oldTimeStamp;
double dist=Math.sqrt(Math.pow(_xDelta,2)+Math.pow(_yDelta,2));
double speed=dist/diff;
textView.setText("speed: " + speed);
oldTimeStamp=timeStamp;
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
layoutRoot.invalidate();
return true;
}
onDetachedFromWindow
上调用mVelocityTracker.recycle()
。 - Ultimo_m