Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create color changing animation? (Android)

I have a TextView and some text in it. I need to create an animation with 30 seconds duration, and it will slowly change the color of text from green to red. Any ideas?

like image 867
Helisia Avatar asked Oct 06 '13 10:10

Helisia


People also ask

Can you animate on Android?

With over a million downloads, Animation Desk is one of the best animation apps for Android that you can try. It has all the things that make an animation app great—a clutter-free user interface, an adequate amount of options, and a handful of ways to export the finished animation.


2 Answers

1) 30s is a really, really long time, hardly any users would wait to see the end of it.

2) See Animating with ObjectAnimator. Something like ObjectAnimator.ofInt(textView, "textColor", Color.GREEN, Color.RED) should do what you want. Note, however, that the transition will be linear and will go through a lot of intermediary colors. until it hits #FF0000. You can of course specify the points in the middle but in general linear color transitions (in RGB) are not pretty.

like image 170
Delyan Avatar answered Nov 07 '22 07:11

Delyan


Delyan's solution works, but as he pointed out, the color transition is not smooth. The following code should give you a smooth color transition:

    public static void changeTextColor(final TextView textView, int startColor, int endColor,
                                   final long animDuration, final long animUnit){
    if (textView == null) return;

    final int startRed = Color.red(startColor);
    final int startBlue = Color.blue(startColor);
    final int startGreen = Color.green(startColor);

    final int endRed = Color.red(endColor);
    final int endBlue = Color.blue(endColor);
    final int endGreen = Color.green(endColor);

    new CountDownTimer(animDuration, animUnit){
        //animDuration is the time in ms over which to run the animation
        //animUnit is the time unit in ms, update color after each animUnit

        @Override
        public void onTick(long l) {
            int red = (int) (endRed + (l * (startRed - endRed) / animDuration));
            int blue = (int) (endBlue + (l * (startBlue - endBlue) / animDuration));
            int green = (int) (endGreen + (l * (startGreen - endGreen) / animDuration));

            Log.d("Changing color", "Changing color to RGB" + red + ", " + green + ", " + blue);
            textView.setTextColor(Color.rgb(red, green, blue));
        }

        @Override
        public void onFinish() {
            textView.setTextColor(Color.rgb(endRed, endGreen, endBlue));
        }
    }.start();
}
like image 44
Vaibhav Gupta Avatar answered Nov 07 '22 07:11

Vaibhav Gupta