如何使用onScroll和GestureDetector - Android跟随我的手指

时间:2012-02-04 01:42:05

标签: android textview gesturedetector onscroll

我有一个RelativeLayout,中间有一个TextView。我已经使用SimpleOnGestureListener()来检测onFling,onDown和onScroll事件。

我希望TextView能够在屏幕周围跟随我的手指(可以只是在x轴上),当我抬起手指时,可以将其设置为从屏幕移出或返回到中间(取决于多远)我已经搬了它。)

1 个答案:

答案 0 :(得分:15)

这是我在这些情况下通常做的事情。

首先,你的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;
}

我们正在修改leftMargintopMargin相当于已滚动距离的金额。

接下来,要使文字视图动画回原始位置,您需要在事件为ACTION_UPACTION_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);
    }
}

那应该这样做!您可以修改endValueXendValueY变量,以控制抬起手指时文本视图的返回位置。