Animate change of view background color on Android

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

Leave a Comment