import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvTitle;
Button btnStart,btnStop;
ValueAnimator animation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获得组件
tvTitle=(TextView) findViewById(R.id.tv_title_main);
btnStart=(Button) findViewById(R.id.start_anim_main);
btnStop=(Button) findViewById(R.id.stop_anim_main);
//监听事件
btnStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//一。构造并返回0-255之间的一个变化的ValueAnimator
animation=ValueAnimator.ofInt(0,255);
//二。设置动画 的时常
animation.setDuration(3000);
//三。Repeat重复,设置重复的次数
animation.setRepeatCount(ValueAnimator.INFINITE);
//四。设置重复的模板(当这个动画到结尾时,应该如何做)
animation.setRepeatMode(ValueAnimator.RESTART);
//设置动画更新的监听事件
animation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//五。获取当前时刻animation的值
Log.i("Tag", ""+animation.getAnimatedValue());
int red=Color.rgb((Integer) animation.getAnimatedValue(), 0, 0);
//六 。把获得的值设置为TextView的颜色值
tvTitle.setTextColor(red);
}
});
//开始动画
animation.start();
}
});
btnStop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(animation.isRunning()){//如果animation动画正在运行
animation.end();//结束
}
}
});
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv_title_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="35sp" />
<Button
android:id="@+id/start_anim_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_title_main"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="开始属性动画" />
<Button
android:id="@+id/stop_anim_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/start_anim_main"
android:layout_centerVertical="true"
android:text="停止属性动画" />
</RelativeLayout>