美文网首页
属性动画+scrollto scrollby等

属性动画+scrollto scrollby等

作者: zjl20 | 来源:发表于2021-09-27 09:57 被阅读0次

ValueAnimator 提供了一个简单的计时引擎,用于执行动画时根据设置的时长以及其他属相完成动画值的计算,然后就可以将动画值设置到合适的目标对象上,使用的插值器默认时 AccelerateDecelerateInterpolator,表示动画开始和结束时较慢,中间加速完成动画

ValueAnimator 可以使用代码创建,也可以使用 xml 创建,下面以平移动画为例说明 ValueAnimator 的使用方式,其他如缩放、旋转等使用方式类似

ValueAnimator animator = (ValueAnimator) AnimatorInflater.loadAnimator(this,R.animator.test_animator);
animator.setTarget(ivImage);
animator.start();
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Log.i(TAG, animation.getAnimatedValue() + "");
int x = (int) animation.getAnimatedValue();
ivImage.setTranslationX(x);
ivImage.setTranslationY(x);
}
});

setTranslationX和setTranslationY,api版本为11,是设置view相对原始位置的偏移量

上面是api介绍,即相对left position的偏移,所谓left position也即getLeft(),同时可以在xml里直接用android:translationX进行设置。关于view的位置,我们最常用的莫过于android:layoutMargin这一套,用来设置相对父布局的偏移,在java代码里可以通过新建或更新view的LayoutParams进行修改,如下所示:

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)text.getLayoutParams();
params.leftMargin = 0;
params.rightMargin = 0;
params.setMargins(0, 0, 0, 0);
text.setLayoutParams(params);

1,setTranslationX改变了view的位置,但没有改变view的LayoutParams里的margin属性;
2,它改变的是android:translationX 属性,也即这个参数级别是和margin平行的。

使用属性动画后如果想复位
private void resetPos(){
ViewHelper.setTranslationX(text, 0);
}

以控件的左上角为坐标起点 在控件内移动 可视内容不会超出控件空间
scrollTo、scrollBy方法移动的是View的 \color{red}{内容},即让View的内容移动,
如果在ViewGroup中使用scrollTo、scrollBy方法,那么移动的将是所有子View

scrollTo 移动到 固定坐标
scrollby 基于当前位置继续移动多少
滚动的位置对应getSorollY 和getScorollX

\color{red}{scrollto(100,0) getScorollX =100 对应图如下}

653161-20180921105742116-1366895794.png

这也就解释了为什么scrollTo()方法中参数大于0,View向左移动,参数小于0,View向右移动。

getRawX、getRawY与getX、getY的区别
在编写android的自定义控件,或者判断用户手势操作时,往往需要使用MotionEvent中的getRawX()、getRawY()与getX()、getY()取得触摸点在X轴与Y轴上的距离,这四个方法都返回一个float类型的参数,单位为像素(Pixel)。getRawX()、getRawY()返回的是触摸点相对于屏幕的位置,而getX()、getY()返回的则是触摸点相对于View的位置。

以下两张图直观的表现了这几个方法的区别,在屏幕中央放置了一个Button,并为它注册了OnTouchListener,图中绿圆点为触摸点位置。


151519472162825.png 151520058731827.png

相关文章

网友评论

      本文标题:属性动画+scrollto scrollby等

      本文链接:https://www.haomeiwen.com/subject/nqshnltx.html