15
votes

I have a problem. I want to animate the background color of a LinearLayout, using ObjectAnimator.
The problem is that it animates, but it does neither care about duration nor valueFrom and valueTo.

This is my xml file:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:propertyName="backgroundColor"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:valueFrom="#FF0000"
    android:valueTo="#000000" />

In Java I call like this:

ObjectAnimator objAnim = (ObjectAnimator)AnimatorInflater.loadAnimator(getActivity(), R.animator.animator_bkg);
objAnim.setTarget(view);
objAnim.start();

Note that when I animate the alpha of the layout, it works as expected.
Is this an Android bug (4.0.3 on Asus Transformer), or I miss something?

2
What happens exactly when you try to animate the colors?DeeV
The animation speed is very fast, and it looks like the background is animated with all possible colors(like a random color). I see blue, red, green, yellow, everything, and very fast :)XMight
This fails to work because between the "number" 0xFF0000 and 0x000000 there's also the other primary colours 0x00FF00 and 0x0000FF, and pretty much every other colour as well. Set your desktop calculator to programmer/hexadecimal, and you'll see that half of red is actually dark yellow instead of dark red.Combuster

2 Answers

40
votes

I googled a bit. There is an answer. Try to use TransitionDrawable. http://developer.android.com/guide/topics/resources/drawable-resource.html#Transition

Also, there is a topic somewhere on stackoverflow.com dedicated to the same problem.

ADDED Code example:

    Button btn = (Button)this.findViewById(R.id.btn1);
    //Let's change background's color from blue to red.
    ColorDrawable[] color = {new ColorDrawable(Color.BLUE), new ColorDrawable(Color.RED)};
    TransitionDrawable trans = new TransitionDrawable(color);
    //This will work also on old devices. The latest API says you have to use setBackground instead.
    btn.setBackgroundDrawable(trans);
    trans.startTransition(5000);
14
votes

It seems to be an old issue. I stumbled on this question while having a similar problem.

At the end it was just a bug in Android. The code is supposed to work, but the AnimatorInflater just blunders when setting the evaluator.

So setting the TypeEvaluator after the inflation again would do the trick.

    ObjectAnimator objAnim = (ObjectAnimator)AnimatorInflater.loadAnimator(getActivity(), R.animator.animator_bkg);
    objAnim.setTarget(view);
    objAnim.setEvaluator(new ArgbEvaluator());
    objAnim.start();

Set to new ArgbEvaluator() the animation works like intended.