San*_*ndy 9 android textview onscroll gesturedetector
我有一个RelativeLayout,中间有一个TextView.我已经使用SimpleOnGestureListener()来检测onFling,onDown和onScroll事件.
我希望TextView能够在屏幕上跟随我的手指(可以只是在x轴上),当我抬起手指时,它会从屏幕上移动或者回到中间(取决于我有多远)感动它).
mon*_*ote 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;
}
Run Code Online (Sandbox Code Playgroud)
我们正在修改leftMargin
和topMargin
相当于滚动距离的数量.
接下来,要使文本视图动画回原始位置,您需要在事件为ACTION_UP
或时执行此操作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);
}
Run Code Online (Sandbox Code Playgroud)
然后在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);
}
}
Run Code Online (Sandbox Code Playgroud)
那应该做的!您可以修改endValueX
和endValueY
变量来控制抬起手指时文本视图返回的位置.
归档时间: |
|
查看次数: |
7319 次 |
最近记录: |