Animate change of view background color on Android

前端 未结 16 697
孤街浪徒
孤街浪徒 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:09

    Use the below function for 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()
    }
    

    Pass whatever view you want to change color of.

    0 讨论(0)
  • 2020-11-22 14:13

    I've found that the implementation used by ArgbEvaluator in the Android source code does best job in transitioning colors. When using HSV, depending on the two colors, the transition was jumping through too many hues for me. But this method's doesn't.

    If you are trying to simply animate, use ArgbEvaluator with ValueAnimator as suggested here:

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

    However, if you are like me and want to tie your transition with some user gesture or other value passed from an input, the ValueAnimator is not of much help (unless your are targeting for API 22 and above, in which case you can use the ValueAnimator.setCurrentFraction() method). When targeting below API 22, wrap the code found in ArgbEvaluator source code in your own method, as shown below:

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

    And use it however you wish.

    0 讨论(0)
  • 2020-11-22 14:15

    You can use ArgbEvaluatorCompat class above API 11.

    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();
            }
        });
    colorAnimation.start();
    
    0 讨论(0)
  • 2020-11-22 14:16

    Depending on how your view gets its background color and how you get your target color there are several different ways to do this.

    The first two uses the Android Property Animation framework.

    Use a Object Animator if:

    • Your view have its background color defined as a argb value in a xml file.
    • Your view have previously had its color set by view.setBackgroundColor()
    • Your view have its background color defined in a drawable that DOES NOT defines any extra properties like stroke or corner radiuses.
    • Your view have its background color defined in a drawable and you want to remove any extra properties like stroke or corner radiuses, keep in mind that the removal of the extra properties will not animated.

    The object animator works by calling view.setBackgroundColor which replaces the defined drawable unless is it an instance of a ColorDrawable, which it rarely is. This means that any extra background properties from a drawable like stroke or corners will be removed.

    Use a Value Animator if:

    • Your view have its background color defined in a drawable that also sets properties like the stroke or corner radiuses AND you want to change it to a new color that is decided while running.

    Use a Transition drawable if:

    • Your view should switch between two drawable that have been defined before deployment.

    I have had some performance issues with Transition drawables that runs while I am opening a DrawerLayout that I haven't been able to solve, so if you encounter any unexpected stuttering you might have run into the same bug as I have.

    You will have to modify the Value Animator example if you want to use a StateLists drawable or a LayerLists drawable, otherwise it will crash on the final GradientDrawable background = (GradientDrawable) view.getBackground(); line.

    Object Animator:

    View definition:

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

    Create and use a ObjectAnimator like this.

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

    You can also load the animation definition from a xml using a AnimatorInflater like XMight does in Android objectAnimator animate backgroundColor of Layout

    Value Animator:

    View definition:

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

    Drawable definition:

    <?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>
    

    Create and use a ValueAnimator like this:

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

    Transition drawable:

    View definition:

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

    Drawable definition:

    <?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>
    

    Use the TransitionDrawable like this:

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

    You can reverse the animations by calling .reverse() on the animation instance.

    There are some other ways to do animations but these three is probably the most common. I generally use a ValueAnimator.

    0 讨论(0)
  • 2020-11-22 14:16

    Another easy way to achieve this is to perform a fade using AlphaAnimation.

    1. Make your view a ViewGroup
    2. Add a child view to it at index 0, with match_parent layout dimensions
    3. Give your child the same background as the container
    4. Change to background of the container to the target color
    5. Fade out the child using AlphaAnimation.
    6. Remove the child when the animation is complete (using an AnimationListener)
    0 讨论(0)
  • 2020-11-22 14:19

    You can use new Property Animation Api for color animation:

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

    For backward compatibility with Android 2.x use Nine Old Androids library from Jake Wharton.

    The getColor method was deprecated in Android M, so you have two choices:

    • If you use the support library, you need to replace the getColor calls with:

      ContextCompat.getColor(this, R.color.red);
      
    • if you don't use the support library, you need to replace the getColor calls with:

      getColor(R.color.red);
      
    0 讨论(0)
提交回复
热议问题