Skip to main content

Animate change of view background color in Android



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.


Comments

  1. 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">
    <!-- 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!

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?