先来个简单的例子
ObjectAnimator.ofFloat(v, "rotationX", 0f, 360f)
.setDuration(400).start();
v:播放动画的View;
rotationX:播放的方式;
0f:起始值;
360f:结束值;
起始值和结束值之间可以添加中间状态;如播放组合动画中的示例;
默认支持播放动画的列表
rotationX | 沿着X轴旋转 |
rotationY | 沿着Y轴旋转 |
rotation | 沿着Z轴旋转 |
scaleX | 沿着X轴缩放 |
scaleY | 沿着Y轴缩放 |
alpha | 非透明度 |
translationX | 沿着X轴平移 |
播放组合动画
ObjectAnimator oaR = ObjectAnimator.ofFloat(v, "rotationX", 0f, 360f , 0f);
ObjectAnimator oaSx = ObjectAnimator.ofFloat(v, "scaleX", 1f, 0f, 1f);
ObjectAnimator oaSy = ObjectAnimator.ofFloat(v, "scaleY", 1f, 0f, 1f);
ObjectAnimator oaA = ObjectAnimator.ofFloat(v, "alpha", 1f, 0f ,1f);
AnimatorSet set = new AnimatorSet();
set.playTogether(oaR, oaSx, oaSy, oaA);
set.setDuration(800).start();
playTogether | 同时播放 |
before | 在之前播放 |
after | 在之后播放 |
ObjectAnimator oaTx = ObjectAnimator.ofFloat(v, "translationX", 0f, 234f);
ObjectAnimator oaR = ObjectAnimator.ofFloat(v, "rotationY", 0f, 360f , 0f);
ObjectAnimator oaTx2 = ObjectAnimator.ofFloat(v, "translationX", 0f);
AnimatorSet set = new AnimatorSet();
set.setInterpolator(new AccelerateDecelerateInterpolator());
set.play(oaTx).before(oaR).before(oaTx2);
set.setDuration(1200).start();
状态监听
ObjectAnimator oaR = ObjectAnimator.ofFloat(v, "rotation", 0f, 360f);
oaR.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
});
oaR.setDuration(4000).start();
自定义动画
除了使用默认的rotationX等动画之外,也可以自定义一些动画,当然这得配合自定义View;
在自定义View添加对应动画的get/set方法即可;
用ImageView做个简单的例子;
public class MyImageView extends ImageView {
int animValue = 100;
public int getAnimValue() {
return animValue;
}
public void setAnimValue(int value) {
animValue = value;
setTranslationX(value);
setTranslationY(value);
}
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
调用;
ObjectAnimator oaR = ObjectAnimator.ofInt(v, "animValue", 0, 30, 70, 0);
oaR.setDuration(4000).start();