1. 属性动画:顾名思义,就是通过改变View的属性,所形成的动画。先来看看View的几个属性
(1) translationX 和 translationY :通过这两个属性可以改变View沿X轴或Y轴的位置,例如:
ObjectAnimator.ofFloat(v, "translationX ", 0, 20, -20, 0).setDuration(100).start(); // 让View沿X轴方向来回移动20
我们可以在源码中看到,ofFlaot()的第三个参数是float... values,说明可以有多个float类型的参数,上面的例子让v先向右移到坐标20处,再向左移到坐标-20处,最后回到0
(2) rotation、rotationX 和 rotationY:分别让View沿着中心点顺时针旋转、沿着X轴翻转、沿着Y轴翻转。例如:
ObjectAnimator.ofFloat(v, "rotationY", 0.0F, 360.0F).setDuration(500).start(); // 沿着Y轴翻转360度
(3) scaleX 和 scaleY:让View沿着X轴或Y轴方向压缩,例如:
ObjectAnimator.ofFloat(v, "scaleX ", 1F, 0F).setDuration(500).start(); // 1F表示原View大小,0F表示压缩到0
(4) aplha:改变View的透明度,1F表示不透明,0F表示全透明
2. 利用ObjectAnimator的方法实现单个动画
参考第1点的例子
3.利用PropertyValuesHolder实现多个动画同时播放
PropertyValuesHolder a1 = PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f, 1.0f);
PropertyValuesHolder a2 = PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f, 1.0f);
PropertyValuesHolder a3 = PropertyValuesHolder.ofFloat("aplha", 1.0f, 0.0f, 1.0f);
ObjectAnimator.ofPropertyValuesHolder(v, a1, a2, a3).setDuration(1000).start();
4.为动画添加监听器
假如你想让某个图片消失,并不是把它的透明度改成0后它就会消失,我们需要为这个透明动画添加监听器,在动画结束的时候将这个图片去掉,就像下面这样
ObjectAnimator anim = ObjectAnimator.ofFloat(imageView, "alpha", 1.0f, 0.0f);
anim.start();
// 为动画添加监听器
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
Log.i(TAG, "onAnimationStart");
}
@Override
public void onAnimationEnd(Animator animation) {
Log.i(TAG, "onAnimationEnd");
ViewGroup parent = (ViewGroup) imageView.getParent();
if (parent != null)
parent.removeView(imageView); // 将View移除
}
@Override
public void onAnimationCancel(Animator animation) {
Log.i(TAG, "onAnimationCancel");
}
@Override
public void onAnimationRepeat(Animator animation) {
Log.i(TAG, "onAnimationRepeat");
}
});
或者使用
anim.addListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
Log.e(TAG, "onAnimationEnd");
ViewGroup parent = (ViewGroup) imageView.getParent();
if (parent != null)
parent.removeView(imageView);
}
});