版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/true100/article/details/82885900
Android系统提供的帧动画和 View 动画提供了 AlphaAnimation、RotateAnimation、TranslateAnimation、ScaleAnimation这4种动画方式,并提供了AnimationSet动画集合来混合使用多种动画。实现起来非常方便,但有人最明显的缺陷突显:不具有交互性。某个元素发生View动画后,其响应事件的位置依然在动画进行前的地方,所以出现了属性动画。属性动画通过调用属性get、set方法来真实地控制一个View的属性值,是真正意义上的实现了动画效果。
public class AnimatorActivity extends Activity {
private TextView animator_tv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animator_tv = findViewById(R.id.animator_tv);
//第一种方式
//第二种方式
}
/**
* AnimatorSet实现组合动画
* AnimatorSet可以指定动画同时或按顺序执行
*/
private void animatorStyleOne() {
//X方向平移
ObjectAnimator translateXAnimaotr = ObjectAnimator.ofFloat(animator_tv, "translationX", 0f, 200f);
//Y方向平移
ObjectAnimator translateYAnimaotr = ObjectAnimator.ofFloat(animator_tv, "translationY", 0f, 300f);
//实现旋转动画,也可以单独使用rotationX或rotationY
//rotationX 表示围绕 X 轴旋转
//rotationY:表示围绕 Y 轴旋转
//rotation:表示围绕 Z 旋转
ObjectAnimator rotationAnimaotr = ObjectAnimator.ofFloat(animator_tv, "rotation", 0f, 360f, 0f);
//缩放动画,也有X及Y两个方向上设置
ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(animator_tv, "scaleX", 1f, 3f);
ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(animator_tv, "scaleY", 1f, 3f);
//透明度动画
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(animator_tv, "alpha", 0.5f, 1f);
//然后通过AnimatorSet把几种动画组合起来
AnimatorSet animatorSet = new AnimatorSet();
/**
* AnimatorSet正是通过以下方法来控制动画播放顺序:
* after(Animator anim):将现有动画插入到传入的动画之后执行。
* before(Animator anim):将现有动画插入到传入的动画之前执行。
* with(Animator anim):将现有动画和传入的动画同时执行。
*/
animatorSet.play(translateXAnimaotr).with(translateYAnimaotr).before(rotationAnimaotr).after(scaleXAnimator).with(scaleYAnimator).after(alphaAnimator);
//设置动画时间
animatorSet.setDuration(2000);
//开始动画
animatorSet.start();
}
/**
* PropertyValuesHolder实现组合动画
* PropertyValuesHolder类只能是多个动画一起执行
*/
private void animatorStyleTwo() {
//X方向平移
PropertyValuesHolder translateXAnimaotr = PropertyValuesHolder.ofFloat("translationX", 0f, 200f);
//Y方向平移
PropertyValuesHolder translateYAnimaotr = PropertyValuesHolder.ofFloat("translationY", 0f, 300f);
//实现旋转动画,也可以单独使用rotationX或rotationY
//rotationX 表示围绕 X 轴旋转
//rotationY:表示围绕 Y 轴旋转
//rotation:表示围绕 Z 旋转
PropertyValuesHolder rotationAnimaotr = PropertyValuesHolder.ofFloat("rotation", 0f, 360f, 0f);
//缩放动画,也有X及Y两个方向上设置
PropertyValuesHolder scaleXAnimator = PropertyValuesHolder.ofFloat("scaleX", 1f, 3f);
PropertyValuesHolder scaleYAnimator = PropertyValuesHolder.ofFloat("scaleY", 1f, 3f);
//透明度动画
PropertyValuesHolder alphaAnimator = PropertyValuesHolder.ofFloat("alpha", 0.5f, 1f);
ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(animator_tv, translateXAnimaotr, translateYAnimaotr, rotationAnimaotr, scaleXAnimator, scaleYAnimator);
objectAnimator.setDuration(2000);
objectAnimator.start();
}
}