Android 颜色渐变动画
时间: 2023-10-13 21:28:55 浏览: 140
Android中可以使用GradientDrawable类实现颜色渐变动画。下面是一个简单的例子:
1.在res/drawable目录下新建一个gradient.xml文件,内容如下:
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:startColor="#FF0000"
android:endColor="#0000FF"
android:type="linear"
android:angle="0"/>
</shape>
```
这个文件定义了一个线性渐变,起始颜色为红色,结束颜色为蓝色。
2.在需要使用渐变效果的View中设置背景为gradient.xml,例如:
```
Button button = findViewById(R.id.button);
button.setBackgroundResource(R.drawable.gradient);
```
3.使用ValueAnimator类实现颜色渐变动画,例如:
```
ValueAnimator colorAnimation = ValueAnimator.ofArgb(
ContextCompat.getColor(this, R.color.colorAccent),
ContextCompat.getColor(this, R.color.colorPrimary)
);
colorAnimation.setDuration(3000);
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
button.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
```
这个例子实现了一个从蓝色到红色的颜色渐变动画,时长为3秒。在动画更新的回调中,设置View的背景颜色为动画的当前值。
阅读全文
相关推荐















