我有一个RelativeLayout,其中包含一个位于中间的TextView。我已经使用SimpleOnGestureListener()使其检测到onFling、onDown和onScroll事件。
我希望TextView能够跟随我的手指在屏幕上移动(仅限于x轴),当我松开手指时,它可以动画地移出屏幕或回到中间(取决于我移动了多远)。
我有一个RelativeLayout,其中包含一个位于中间的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;
}
@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
变量,以控制在放开手指后文本视图返回的位置。
if(distanceX > 5){ marginLayoutParams.leftMargin = (int)marginLayoutParams.leftMargin - distanceX;
- Saba Jamalian