android - Android上 View 背景颜色的动画变化

标签 android animation view background-color

如何在 Android 上为 View 的背景颜色变化设置动画?

例如:

我有一个红色背景色的 View 。 View 的背景颜色变为蓝色。如何在颜色之间进行平滑过渡?

如果 View 无法做到这一点,欢迎使用替代方法。

最佳答案

您可以使用新的 Property Animation Api彩色动画:

int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
        textView.setBackgroundColor((int) animator.getAnimatedValue());
    }

});
colorAnimation.start();

为了向后兼容 Android 2.x,请使用 Nine Old Androids library来自 jack 沃顿。

getColor 方法在 Android M 中已弃用,因此您有两种选择:

  • 如果您使用支持库,则需要将 getColor 调用替换为:

    ContextCompat.getColor(this, R.color.red);
    
  • 如果您不使用支持库,则需要将 getColor 调用替换为:

    getColor(R.color.red);
    

关于android - Android上 View 背景颜色的动画变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614545/

相关文章:

CSS3 多动画(webkit 关键帧)同步问题

android - 如何在不阻塞主线程的情况下制作流畅的动画?

MySQL View,从存储过程获取结果

python - 基于类的 View 中使用了哪些预定义的 Django 方法

android - View 和 subview 之间的区别 - Android

android - Android Studio错误:未知主机 'service.gradle.org'

android - 如何在 Android 中获取像素颜色?

Android:不启动启动器 - 在启动时运行我的应用程序

java - 为 Android 应用程序设置服务器

html - 带有动画转换的 z-index 错误