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 view changes to blue. How can I do a smooth transition between colors?
If this can't be done with views, an alternative will be welcome.
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);