Android ObjectAnimator基础用法

视图动画存在的缺陷,动画发生后,事件的响应还留在动画发生前,而属性动画可以解决这一问题。
使用 ObjectAnimator进行平移

ObjectAnimator.ofFloat(imageView, "translationX", 500).setDuration(300).start();


以下是属性动画常用属性值:
translationX和translationY:作为一种增量来控制View对象从他容器的左上角坐标偏移的位置
rotation rotationX和rotationY:控制View围绕支点进行2D和3D的旋转
scaleX和scaleY:控制View围绕他的支点进行2D旋转
pivotX和pivotY:控制View对象的支点位置,围绕这个支点进行旋转和缩放的处理,默认情况下支点位置为对象的中心点


如果一个属性没有get和set方法可以通过包裹类来实现。
public class WrapperView { private View mTarget; public WrapperView(View target) { this.mTarget = target; } public int getWidth(){ return mTarget.getLayoutParams().width; } public void setWidth(int width){ mTarget.getLayoutParams().width = width; mTarget.requestLayout(); } }

调用:

WrapperView wrapper = new WrapperView(imageView); ObjectAnimator.ofInt(wrapper, "width", 500).setDuration(300) .start();



针对同一个对象同时实现多个动画:
使用PropertyValuesHolder实现:


PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat( "translationX", 100f, 300f); PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat( "scaleX", 1f, 0, 1f); PropertyValuesHolder pvh3 = PropertyValuesHolder.ofFloat( "scaleY", 1f, 0, 1f); ObjectAnimator .ofPropertyValuesHolder(imageView, pvh1, pvh2, pvh3) .setDuration(300).start();

AnimatinSet可以进行更为精准的顺序控制

使用AnimatinSet实现:

ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "translationX", 100f, 300f); ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "scaleX", 1f, 0, 1f); ObjectAnimator animator3 = ObjectAnimator.ofFloat(imageView, "scaleY", 1f, 0, 1f); AnimatorSet set = new AnimatorSet(); set.setDuration(1000); set.playTogether(animator1, animator2, animator3); set.start();


AnimatorSet还可以使用playSequentially(animator1,animator2,...)来实现连续动画,使用play(animator1).with(animator2).before(anmiator3).after(animator4)来控制动画顺序



在xml中使用ObjectAniamtor


在程序中使用:

Animator anim = AnimatorInflater.loadAnimator( MainActivity.this, R.anim.objectanimator); anim.setTarget(imageView); anim.start();



【Android ObjectAnimator基础用法】

    推荐阅读