views:

662

answers:

1

How do you animate the change of background color of a view in 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.

+1  A: 

I ended up figuring out a (pretty good) solution for this problem!

You can use a TransitionDrawable to accomplish this. For example, in an xml file in the drawable folder you could write something like:

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
    <item android:drawable="@drawable/original_state" />
    <item android:drawable="@drawable/new_state" />
</transition>

Then, in your xml for the actual View you would reference this TransitionDrawable in the android:background attribute.

At this point you can initiate the transition in your code on-command by doing:

TransitionDrawable transition = (TransitionDrawable) viewObj.getBackground();
transition.startTransition(transitionTime);

Or run the transition in reverse by calling:

transition.reverseTransition(transitionTime);

I hope this helps you solve your problem!

mxrider
Thanks mxrider! This does answer the question. Unfortunately it doesn't work for me because the view that has the TransitionDrawable as background has to be animated as well, and it seems that the view animation overrides the background transition. Any ideas?
hgpc
Solved it by starting the TransitionDrawable AFTER starting the animation.
hgpc
Awesome! Glad you got it working! There is a lot of cool stuff you can do in xml with Android--much of which is kinda buried in the docs and not obvious in my opinion.
mxrider
Not obvious at all. I should mention that I'm not using xml in my case, as the color is dynamic. Your solution also works if you create the TransitionDrawable by code.
hgpc