MainActivity如下:
package cc.cn; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import android.animation.AnimatorInflater; import android.animation.ArgbEvaluator; import android.animation.ObjectAnimator; import android.app.Activity; import android.content.Context; /** * Demo描述: * 利用Property Animation(属性动画)使组件的背景色渐变 * * 参考资料 * 1 Android疯狂讲义(第二版) 作者李刚 * 2 http://blog.csdn.net/think_soft/article/details/7703684 * 3 http://www.cnblogs.com/angeldevil/archive/2011/12/02/2271096.html * 4 http://blog.csdn.net/think_soft/article/details/7713757 * 5 http://wiki.eoeandroid.com/Property_Animation * 关于TypeEvaluator请参见资料2,3,4 * 6 关于属性动画的中文文档,请参见: * http://blog.csdn.net/think_soft/article/details/7703684 * http://wiki.eoeandroid.com/Property_Animation * Thank you very much * */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ RelativeLayout relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayout); AnimationView animationView=new AnimationView(this); //为根布局添加一个自定义控件 relativeLayout.addView(animationView); } //自定义控件 //这个思路是很好的: //在自定义控件的构造方法中为该控件设置一个属性动画. //所以该动画会一直伴随着该自定义控件. public class AnimationView extends View{ public AnimationView(Context context) { super(context); ObjectAnimator objectAnimator= (ObjectAnimator) AnimatorInflater.loadAnimator(MainActivity.this, R.animator.coloranimation); //为该属性动画设置了TypeEvaluator为一个ARGB类型的TypeEvaluator!!!!! //注意我们在 R.animator.coloranimation中设置了属性:android:propertyName="backgroundColor" //这两者结合起来表示:我们这个属性动画要改变的属性是backgroundColor,且该属性值变化的方式(类型) //是依据ARGB进行的 objectAnimator.setEvaluator(new ArgbEvaluator()); objectAnimator.setTarget(this); objectAnimator.start(); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" > </RelativeLayout>
coloranimation.xml如下:
<?xml version="1.0" encoding="utf-8"?> <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:propertyName="backgroundColor" android:duration="5000" android:valueFrom="#ff0033" android:valueTo="#000099" android:repeatCount="infinite" android:repeatMode="reverse" android:valueType="intType"> </objectAnimator>