属性动画在Android 3.0中引入,为开发者提供了更强的自定义动画的能力,属性动画在游戏开发中比较常见。下面是演示一副图像的宽度的例子:
代码:属性动画的实例
package com.miaozl.test2;
import android.animation.IntEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class PropertyAnimActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout root= ((LinearLayout) this.findViewById(R.id.animlayout));
ImageAnimView imageAnim = new ImageAnimView(this);
imageAnim.setImageResource(R.drawable.photo3);
root.addView(imageAnim);
}
private class ImageAnimView extends ImageView {
public ImageAnimView(Context context) {
super(context);
// TODO Auto-generated constructor stub
ValueAnimator valueAnim = ObjectAnimator.ofInt(this, "width", 0, 200);
valueAnim.setDuration(3000); //持续时间
valueAnim.setEvaluator(new IntEvaluator());//设置演进器
valueAnim.setRepeatCount(ValueAnimator.INFINITE);//设置重复数
valueAnim.setRepeatMode(ValueAnimator.REVERSE);//设置重复模式
valueAnim.start();
}
}
}
在Android中,目前定义了三种类型的演进器:ArgbEvaluator、FloatEvaluator、IntEvaluator等。如果用于动画的属性不是int、float、color类型的。开发者可以扩展TypeEvaluator接口来计算目标对象的属性变化。