我有一个相对布局,中间有一个 TextView。我已经使用 SimpleOnGestureListener() 来检测 onFling、onDown 和 onScroll 事件。
我希望 TextView 在屏幕上跟随我的手指(可以只是在 x 轴上),当我抬起手指时,动画要么离开屏幕,要么回到中间(取决于我有多远)移动它)。
我有一个相对布局,中间有一个 TextView。我已经使用 SimpleOnGestureListener() 来检测 onFling、onDown 和 onScroll 事件。
我希望 TextView 在屏幕上跟随我的手指(可以只是在 x 轴上),当我抬起手指时,动画要么离开屏幕,要么回到中间(取决于我有多远)移动它)。
这是我通常在这些情况下所做的。
首先,您的 onScroll 方法应如下所示:
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
// Make sure that mTextView is the text view you want to move around
if (!(mTextView.getLayoutParams() instanceof MarginLayoutParams))
{
return false;
}
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) mTextView.getLayoutParams();
marginLayoutParams.leftMargin = (int) marginLayoutParams.leftMargin - distanceX;
marginLayoutParams.topMargin = (int) marginLayoutParams.topMargin - distanceY;
mTextView.requestLayout();
return true;
}
我们正在修改leftMargin
和topMargin
相当于已滚动距离的数量。
接下来,要使文本视图动画回其原始位置,您需要在事件为ACTION_UP
or时执行此操作ACTION_CANCEL
:
@Override
public boolean onTouch(View arg0, MotionEvent event)
{
if (event.getActionMasked() == MotionEvent.ACTION_UP || event.getActionMasked() == MotionEvent.ACTION_CANCEL)
{
snapBack();
}
return mScrollDetector.onTouchEvent(event);
}
然后在 snapBack 方法中,我们动画回文本视图:
private void snapBack ()
{
if (mTextView.getLayoutParams() instanceof MarginLayoutParams)
{
final MarginLayoutParams marginLayoutParams = (MarginLayoutParams) mTextView.getLayoutParams();
final int startValueX = marginLayoutParams.leftMargin;
final int startValueY = marginLayoutParams.topMargin;
final int endValueX = 0;
final int endValueY = 0;
mTextView.clearAnimation();
Animation animation = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
int leftMarginInterpolatedValue = (int) (startValueX + (endValueX - startValueX) * interpolatedTime);
marginLayoutParams.leftMargin = leftMarginInterpolatedValue;
int topMarginInterpolatedValue = (int) (startValueY + (endValueY - startValueY) * interpolatedTime);
marginLayoutParams.topMargin = topMarginInterpolatedValue;
mTextView.requestLayout();
}
};
animation.setDuration(200);
animation.setInterpolator(new DecelerateInterpolator());
mTextView.startAnimation(animation);
}
}
应该这样做!您可以修改endValueX
和endValueY
变量来控制当您抬起手指时文本视图返回的位置。