Android属性动画使用详解

我们平常用到的大多数都是传统动画,简单的平移、旋转、透明度等动画效果,但是这种传统的动画有一个致命的缺点,就是不是真正意义上的改变了属性,而是效果出现了,属性没有变化。举个例子,你平移一个按钮,在按钮上加一个点击事件,那么等按钮平移完了之后,点击事件的响应其实还是在原地的,你点击它平移之后的地方是没有响应的。Google也考虑了这一点,所以在在3.0之后加入了一个属性动画的概念,让我们一起领略一下属性动画吧。

在开发过程中,最常用的就是ObjectAnimator了,那么他到底应该怎么用呢?

一、透明度动画

ObjectAnimator animator1 = ObjectAnimator.ofFloat(button, "alpha", 1F, 0F);
//执行时间为5秒完成
animator1.setDuration(5000);
//延迟2秒之后执行
animator1.setStartDelay(2000);
//重读次数为2次
animator1.setRepeatCount(2);
//执行完了在倒叙执行回来
animator1.setRepeatMode(Animation.REVERSE);
 创建ObjectAnimator时需要传入三个参数,第一个是动画依附的控件,就是哪一个控件需要动画效果,就把谁的初始化传进去。第二个是动画效果,这里注意他是一个字符串,alpha就是我们熟悉的透明度变化,其他属性都有详细的注释,让我们一起看一下效果 
 

其实道理和传统的动画差不多,相信大家一看就会

二、平移动画

ObjectAnimator animator = ObjectAnimator.ofFloat(button, "translationY", 0F, 400F);
//执行时间为5秒完成
animator.setDuration(5000);
//重读次数为2次
animator.setRepeatCount(2);
//执行完了在倒叙执行回来
animator.setRepeatMode(Animation.REVERSE);
//延迟3秒之后执行
animator.setStartDelay(2000);
//插值器的使用(小球落地弹起的动画)
animator.setInterpolator(new BounceInterpolator());
//执行动画
animator.start();
代码结构和透明度动画结构差不多,只是多了个插值器,效果更炫了,稍后来说一下插值器,我们先看一下效果

因为是插值器的原因,所以会有一个小球自由落体的效果,其实插值器有很多的效果,详细请看我的另外一篇 属性动画的插值器效果

二、旋转动画

ObjectAnimator animator = ObjectAnimator.ofFloat(button, "rotationY", 0F, 360F);
//执行时间为5秒完成
animator.setDuration(5000);
//重读次数为2次
animator.setRepeatCount(2);
//执行完了在倒叙执行回来
animator.setRepeatMode(Animation.REVERSE);
//延迟3秒之后执行
animator.setStartDelay(2000);
animator.start();
看一下效果图



其实动画的实现都是大同小异,一般比较炫酷的动画都是组合一起使用的,我们应该怎么把这几种动画组合起来使用呢,在传统动画中有一个AnimationSet的概念,用来存放动画的一个集合,其实属性动画也有,他就是AnimatorSet,让我们一起来看一下吧

三、平移动画

ObjectAnimator animator1 = ObjectAnimator.ofFloat(button, "alpha", 1F, 0F);
//执行时间为5秒完成
animator1.setDuration(5000);
//重读次数为2次
animator1.setRepeatCount(2);
//执行完了在倒叙执行回来
animator1.setRepeatMode(Animation.REVERSE);

ObjectAnimator animator2 = ObjectAnimator.ofFloat(button, "rotationY", 0F, 360F);
//执行时间为5秒完成
animator2.setDuration(5000);
//重读次数为2次
animator2.setRepeatCount(2);
//执行完了在倒叙执行回来
animator2.setRepeatMode(Animation.REVERSE);

ObjectAnimator animator3 = ObjectAnimator.ofFloat(button, "translationY", 0F, 400F);
//执行时间为5秒完成
animator3.setDuration(5000);
//重读次数为2次
animator3.setRepeatCount(2);
//执行完了在倒叙执行回来
animator3.setRepeatMode(Animation.REVERSE);
//插值器的使用(小球落地弹起的动画)
animator3.setInterpolator(new BounceInterpolator());

AnimatorSet set = new AnimatorSet();
set.playTogether(animator1, animator2, animator3);
set.start();


 我们把三种动画用AnimatorSet放在了一起,来看一些效果 
 



其实每种动画都有一个animator.setStartDelay(2000);属性,作用是动画延迟多长时间之后执行,我们可以根据这个属性来调整我们的先后顺序,做出更完美的动画,其实属性动画不仅仅会这些东西,还有一些更好玩的东西等待我们一起挖掘,相信你们能做出更加优秀的动画,以后再也不用担心动画的问题了

Demo点击打开链接

猜你喜欢

转载自blog.csdn.net/u014752325/article/details/51198332