ObjectAnimator

本文介绍了Android中ObjectAnimator的使用,从一个简单的例子开始,展示了如何播放旋转动画。接着探讨了ObjectAnimator支持的默认动画列表,如何组合播放动画,以及如何添加状态监听。最后提到了如何自定义动画,强调在自定义View中添加对应动画的get/set方法来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先来个简单的例子

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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值