Animate change of view background color on Android

前端 未结 16 968
孤街浪徒
孤街浪徒 2020-11-22 13:23

How do you animate the change of background color of a view on Android?

For example:

I have a view with a red background color. The background color of the

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 14:07

    Here's a nice function that allows this:

    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();
        }
    }
    

    And in 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()
        }
    }
    

提交回复
热议问题