Animate change of view background color on Android

前端 未结 16 981
孤街浪徒
孤街浪徒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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);
      

提交回复
热议问题