376

你如何为Android上视图的背景颜色变化设置动画?

例如:

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

如果这不能通过视图来完成,那么欢迎使用替代方法。

4

18 回答 18

548

您可以使用新的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,请使用来自 Jake Wharton 的九个旧 Android 库。

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

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

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

    getColor(R.color.red);
    
于 2013-01-22T20:42:50.803 回答
417

我最终为这个问题找到了一个(相当不错的)解决方案!

您可以使用TransitionDrawable来完成此操作。例如,在可绘制文件夹中的 XML 文件中,您可以编写如下内容:

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
    <item android:drawable="@drawable/original_state" />
    <item android:drawable="@drawable/new_state" />
</transition>

然后,在实际 View 的 XML 中,您将在android:background属性中引用此 TransitionDrawable。

此时,您可以通过执行以下操作在您的代码命令中启动转换:

TransitionDrawable transition = (TransitionDrawable) viewObj.getBackground();
transition.startTransition(transitionTime);

或者通过调用反向运行转换:

transition.reverseTransition(transitionTime);

有关使用 Property Animation API 的另一种解决方案,请参阅Roman 的答案,该答案在最初发布此答案时不可用。

于 2010-07-08T23:29:39.177 回答
144

根据您的视图如何获得其背景颜色以及您如何获得目标颜色,有几种不同的方法可以做到这一点。

前两个使用Android 属性动画框架。

在以下情况下使用对象动画师

  • 您的视图将其背景颜色定义为argbxml 文件中的值。
  • 您的视图之前的颜色设置为view.setBackgroundColor()
  • 您的视图在可绘制对象中定义了其背景颜色,该可绘制对象不定义任何额外的属性,例如笔划或角半径。
  • 您的视图在可绘制对象中定义了其背景颜色,并且您想要删除任何额外的属性,例如笔划或角半径,请记住,额外属性的删除不会动画。

对象动画师通过调用view.setBackgroundColorwhich 替换定义的可绘制对象来工作,除非它是 a 的实例ColorDrawable,但它很少是。这意味着来自可绘制对象的任何额外背景属性(如笔划或角)都将被删除。

在以下情况下使用Value Animator

  • 您的视图在可绘制对象中定义了其背景颜色,该可绘制对象还设置了笔划或角半径等属性,并且您希望将其更改为运行时确定的新颜色。

在以下情况下使用过渡可绘制对象

  • 您的视图应该在部署之前定义的两个可绘制对象之间切换。

我在打开一个我无法解决的 DrawerLayout 时运行的 Transition drawables 遇到了一些性能问题,所以如果您遇到任何意外的口吃,您可能会遇到与我相同的错误。

如果要使用StateLists drawableLayerLists drawable ,则必须修改 Value Animator 示例,否则它将final GradientDrawable background = (GradientDrawable) view.getBackground();在线崩溃。

对象动画师

查看定义:

<View
    android:background="#FFFF0000"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

创建和使用ObjectAnimator这样的。

final ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(view,
                                                                       "backgroundColor",
                                                                       new ArgbEvaluator(),
                                                                       0xFFFFFFFF,
                                                                       0xff78c5f9);
backgroundColorAnimator.setDuration(300);
backgroundColorAnimator.start();

您还可以使用 AnimatorInflater 从 xml 加载动画定义,就像 XMight 在Android objectAnimator animate backgroundColor of Layout

价值动画师

查看定义:

<View
    android:background="@drawable/example"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

可绘制定义:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke
        android:color="#edf0f6"
        android:width="1dp"/>
    <corners android:radius="3dp"/>

</shape>

像这样创建和使用 ValueAnimator:

final ValueAnimator valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(),
                                                           0xFFFFFFFF,
                                                           0xff78c5f9);

final GradientDrawable background = (GradientDrawable) view.getBackground();
currentAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(final ValueAnimator animator) {
        background.setColor((Integer) animator.getAnimatedValue());
    }

});
currentAnimation.setDuration(300);
currentAnimation.start();

过渡可绘制

查看定义:

<View
    android:background="@drawable/example"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

可绘制定义:

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="#FFFFFF"/>
            <stroke
                android:color="#edf0f6"
                android:width="1dp"/>
            <corners android:radius="3dp"/>
        </shape>
    </item>

    <item>
        <shape>
            <solid android:color="#78c5f9"/>
            <stroke
                android:color="#68aff4"
                android:width="1dp"/>
            <corners android:radius="3dp"/>
        </shape>
    </item>
</transition>

像这样使用 TransitionDrawable:

final TransitionDrawable background = (TransitionDrawable) view.getBackground();
background.startTransition(300);

您可以通过调用.reverse()动画实例来反转动画。

还有其他一些制作动画的方法,但这三种可能是最常见的。我通常使用 ValueAnimator。

于 2013-09-10T15:36:05.393 回答
60

您可以制作对象动画师。例如,我有一个 targetView,我想改变你的背景颜色:

int colorFrom = Color.RED;
int colorTo = Color.GREEN;
int duration = 1000;
ObjectAnimator.ofObject(targetView, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo)
    .setDuration(duration)
    .start();
于 2014-09-05T20:17:43.613 回答
27

如果你想要这样的彩色动画,

在此处输入图像描述

此代码将帮助您:

ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   
anim.setDuration(2000);

float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {

        hsv[0] = 360 * animation.getAnimatedFraction();

        runColor = Color.HSVToColor(hsv);
        yourView.setBackgroundColor(runColor);
    }
});

anim.setRepeatCount(Animation.INFINITE);

anim.start();
于 2015-12-23T06:03:00.600 回答
19

最好的方法是使用ValueAnimatorColorUtils.blendARGB

 ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
 valueAnimator.setDuration(325);
 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

              float fractionAnim = (float) valueAnimator.getAnimatedValue();

              view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
                                    , Color.parseColor("#000000")
                                    , fractionAnim));
        }
});
valueAnimator.start();
于 2017-10-24T12:37:27.447 回答
17

XML 驱动动画的文档很糟糕。我已经搜索了大约几个小时,只是为了在按下按钮时为按钮的背景颜色设置动画......可悲的是,动画只有一个属性:您可以exitFadeDurationselector

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:exitFadeDuration="200">

    <item android:state_pressed="true">
        <shape android:tint="#3F51B5" />
    </item>

    <item>
        <shape android:tint="#F44336" />
    </item>

</selector>

然后将其用作background您的视图。不需要 Java/Kotlin 代码。

于 2019-10-04T14:58:56.103 回答
13

实现此目的的另一种简单方法是使用 AlphaAnimation 执行淡入淡出。

  1. 使您的视图成为 ViewGroup
  2. 在索引 0 处添加一个子视图,具有 match_parent 布局尺寸
  3. 给你的孩子和容器一样的背景
  4. 将容器的背景更改为目标颜色
  5. 使用 AlphaAnimation 淡出孩子。
  6. 动画完成后移除子项(使用 AnimationListener)
于 2012-04-26T13:08:14.200 回答
10

这是我在 Base Activity 中用来更改背景的方法。我正在使用代码中生成的 GradientDrawables,但可以进行调整以适应。

    protected void setPageBackground(View root, int type){
        if (root!=null) {
            Drawable currentBG = root.getBackground();
            //add your own logic here to determine the newBG 
            Drawable newBG = Utils.createGradientDrawable(type); 
            if (currentBG==null) {
                if(Build.VERSION.SDK_INT<Build.VERSION_CODES.JELLY_BEAN){
                    root.setBackgroundDrawable(newBG);
                }else{
                    root.setBackground(newBG);
                }
            }else{
                TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{currentBG, newBG});
                transitionDrawable.setCrossFadeEnabled(true);
                if(Build.VERSION.SDK_INT<Build.VERSION_CODES.JELLY_BEAN){
                     root.setBackgroundDrawable(transitionDrawable);
                }else{
                    root.setBackground(transitionDrawable);
                }
                transitionDrawable.startTransition(400);
            }
        }
    }

更新:如果有人遇到我发现的相同问题,出于某种原因,在 Android <4.3 上使用setCrossFadeEnabled(true)会导致不希望的白化效果,因此我不得不使用上面提到的@Roman Minenok ValueAnimator 方法切换到 <4.3 的纯色。

于 2014-07-09T11:40:48.610 回答
9

这是一个很好的功能,它允许这样做:

public static void animateBetweenColors(final @NonNull View viewToAnimateItsBackground, final int colorFrom,
                                        final int colorTo, final int durationInMs) {
    final ColorDrawable colorDrawable = new ColorDrawable(durationInMs > 0 ? colorFrom : colorTo);
    ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable);
    if (durationInMs > 0) {
        final ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
        colorAnimation.addUpdateListener(animator -> {
            colorDrawable.setColor((Integer) animator.getAnimatedValue());
            ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable);
        });
        colorAnimation.setDuration(durationInMs);
        colorAnimation.start();
    }
}

在 Kotlin 中:

@JvmStatic
fun animateBetweenColors(viewToAnimateItsBackground: View, colorFrom: Int, colorTo: Int, durationInMs: Int) {
    val colorDrawable = ColorDrawable(if (durationInMs > 0) colorFrom else colorTo)
    ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable)
    if (durationInMs > 0) {
        val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
        colorAnimation.addUpdateListener { animator: ValueAnimator ->
            colorDrawable.color = (animator.animatedValue as Int)
            ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable)
        }
        colorAnimation.duration = durationInMs.toLong()
        colorAnimation.start()
    }
}
于 2014-04-30T08:10:41.480 回答
9

答案以多种方式给出。您还可以使用ofArgb(startColor,endColor).ValueAnimator

对于 API > 21:

int cyanColorBg = ContextCompat.getColor(this,R.color.cyan_bg);
int purpleColorBg = ContextCompat.getColor(this,R.color.purple_bg);

ValueAnimator valueAnimator = ValueAnimator.ofArgb(cyanColorBg,purpleColorBg);
        valueAnimator.setDuration(500);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
              @Override
              public void onAnimationUpdate(ValueAnimator valueAnimator) {
                   relativeLayout.setBackgroundColor((Integer)valueAnimator.getAnimatedValue());
              }
        });
        valueAnimator.start();
于 2018-02-03T04:06:59.627 回答
8

对 Kotlin 使用以下函数:

private fun animateColorValue(view: View) {
    val colorAnimation =
        ValueAnimator.ofObject(ArgbEvaluator(), Color.GRAY, Color.CYAN)
    colorAnimation.duration = 500L
    colorAnimation.addUpdateListener { animator -> view.setBackgroundColor(animator.animatedValue as Int) }
    colorAnimation.start()
}

传递您想要更改颜色的任何视图。

于 2020-02-17T10:52:22.543 回答
6

将文件夹动画师添加到res文件夹中。(名称必须是animator)。添加动画器资源文件。例如res/animator/fade.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:propertyName="backgroundColor"
        android:duration="1000"
        android:valueFrom="#000000"
        android:valueTo="#FFFFFF"
        android:startOffset="0"
        android:repeatCount="-1"
        android:repeatMode="reverse" />
</set>

在 Activity java 文件中,调用它

View v = getWindow().getDecorView().findViewById(android.R.id.content);
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.fade);
set.setTarget(v);
set.start();
于 2018-05-10T11:36:28.313 回答
5

我发现ArgbEvaluatorAndroid 源代码中使用的实现在转换颜色方面做得最好。使用 HSV 时,根据这两种颜色,过渡对我来说跳过了太多的色调。但是这个方法不行。

如果您想简单地制作动画,请按照此处的建议使用ArgbEvaluatorwith :ValueAnimator

ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {

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

});
colorAnimation.start();

但是,如果您像我一样想要将您的过渡与某些用户手势或从输入传递的其他值联系起来,ValueAnimator则没有太大帮助(除非您的目标是 API 22 及更高版本,在这种情况下您可以使用该ValueAnimator.setCurrentFraction()方法)。ArgbEvaluator当目标低于 API 22 时,将源代码中的代码包装在您自己的方法中,如下所示:

public static int interpolateColor(float fraction, int startValue, int endValue) {
    int startA = (startValue >> 24) & 0xff;
    int startR = (startValue >> 16) & 0xff;
    int startG = (startValue >> 8) & 0xff;
    int startB = startValue & 0xff;
    int endA = (endValue >> 24) & 0xff;
    int endR = (endValue >> 16) & 0xff;
    int endG = (endValue >> 8) & 0xff;
    int endB = endValue & 0xff;
    return ((startA + (int) (fraction * (endA - startA))) << 24) |
            ((startR + (int) (fraction * (endR - startR))) << 16) |
            ((startG + (int) (fraction * (endG - startG))) << 8) |
            ((startB + (int) (fraction * (endB - startB))));
}

并随心所欲地使用它。

于 2017-01-16T17:55:37.997 回答
5

您可以像这样使用ValueAnimator

 fun startColorAnimation(v: View) {
    val colorStart = v.solidColor
    val colorEnd = Color.RED
    val colorAnim: ValueAnimator = ObjectAnimator.ofInt(v, "backgroundColor", colorStart, colorEnd)
    colorAnim.setDuration(1000)
    colorAnim.setEvaluator(ArgbEvaluator())
    colorAnim.repeatCount = 1
    colorAnim.repeatMode = ValueAnimator.REVERSE
    colorAnim.start()
}
于 2021-03-09T06:26:56.837 回答
2

Roman Minenok在 kotlin 中回答并作为扩展功能

fun View.colorTransition(@ColorRes startColor: Int, @ColorRes endColor: Int, duration: Long = 250L){
    val colorFrom = ContextCompat.getColor(context, startColor)
    val colorTo =  ContextCompat.getColor(context, endColor)
    val colorAnimation: ValueAnimator = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
    colorAnimation.duration = duration

    colorAnimation.addUpdateListener {
        if (it.animatedValue is Int) {
            val color=it.animatedValue as Int
            setBackgroundColor(color)
        }
    }
    colorAnimation.start()
}

如果您想从当前背景颜色更改为新颜色,那么您可以使用它

fun View.colorTransition(@ColorRes endColor: Int, duration: Long = 250L){
    var colorFrom = Color.TRANSPARENT
    if (background is ColorDrawable)
        colorFrom = (background as ColorDrawable).color

    val colorTo =  ContextCompat.getcolor(context, endColor)
    val colorAnimation: ValueAnimator = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
    colorAnimation.duration = duration

    colorAnimation.addUpdateListener {
        if (it.animatedValue is Int) {
            val color=it.animatedValue as Int
            setBackgroundColor(color)
        }
    }
    colorAnimation.start()
}

用法

myView.colorTransition(R.color.bg_color)
于 2021-03-02T16:05:59.740 回答
1

根据ademar111190 的回答,我创建了这个方法,它将在任何两种颜色之间脉冲视图的背景颜色:

private void animateBackground(View view, int colorFrom, int colorTo, int duration) {


    ObjectAnimator objectAnimator = ObjectAnimator.ofObject(view, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo);
    objectAnimator.setDuration(duration);
    //objectAnimator.setRepeatCount(Animation.INFINITE);
    objectAnimator.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            // Call this method again, but with the two colors switched around.
            animateBackground(view, colorTo, colorFrom, duration);
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    });
    objectAnimator.start();
}
于 2019-11-06T11:14:57.850 回答
1

您可以使用API 11 以上的ArgbEvaluatorCompat类。

implementation 'com.google.android.material:material:1.0.0' 


ValueAnimator colorAnim = ValueAnimator.ofObject(new ArgbEvaluatorCompat(), startColor, endColor);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mTargetColor = (int) animation.getAnimatedValue();
        }
    });
colorAnim.start();
于 2020-09-09T02:41:01.173 回答