Android ObjectAnimator基础用法

本文详细介绍了Android属性动画的工作原理及其实现方式,包括平移、旋转、缩放等常见动画效果的实现方法,并演示了如何使用ObjectAnimator和PropertyValuesHolder进行复杂动画组合。

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

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

使用 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

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="scaleX"
    android:valueFrom="1.0"
    android:valueTo="2.0"
    android:valueType="floatType" >

</objectAnimator>

在程序中使用:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值