package com.test.propertyanimation;
import android.animation.AnimatorInflater;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
/**
* 属性动画 资源 (property Animation)
*
* Ainmator 代表一个属性动画但它是一个抽象类,通常会使用它的子类,
* AinmatorSet, ValueAinmator, ObjectAinmator, TimeAinmator.
*
* 定义属性动画的xml资源文件,能以如下三个元素中的任意一个作为根元素.
* 1. <set .../> 它是一个父元素,用于包含其他<objectAnimator.../> <animator.../> 或 <set.../>子元素
* 该元素定义的资源代表 AinmatorSet对象.
* 2.<objectAnimator.../> :用于 ObjectAinmator 动画.
* 3.<animator.../> 用于定义 ValueAinmator 动画.
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout container = (LinearLayout) findViewById(R.id.container);
//添加 MyAnimationView 组件
container.addView(new MyAnimationView(this));
}
public class MyAnimationView extends View {
public MyAnimationView(Context context) {
super(context);
//加载动画资源
ObjectAnimator colorAnim = (ObjectAnimator) AnimatorInflater.loadAnimator(MainActivity.this,R.animator.color_anim);
colorAnim.setEvaluator(new ArgbEvaluator());
//对该view本身应用属性动画
colorAnim.setTarget(this); //上下文设置成 this
//开启动画
colorAnim.start();
}
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container"
>
</LinearLayout>
动画资源
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="backgroundColor"
android:duration="3000"
android:valueFrom="#f00"
android:valueTo="#0f0"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:valueType="intType">
</objectAnimator>
上面的程序 MyAnimationView 本身应用该动画,将可以看到该组件的背景颜色不断变化.