About a week ago I wrote a post about the property animation features added to Android in release 8 (Honeycomb) of the SDK. The post generated enough response from TechRepublic readers that I thought it warranted another tutorial. This time, I wanted to touch on a less frequently demonstrated capability of the class: the ability to interpolate between two color values.

Picking up where we left off last time, the implementation should be a snap. The goal is to create a button that transforms between two background colors over a period of time to create a “pulsing” effect. You can follow along with the brief walk-thru below, or download and import the entire project directly into Eclipse.

1. Create a new Android project in Eclipse.  You must target at least version 8 of the SDK. Be sure to rename your startup activity to Main.java, and the corresponding layout to main.xml.

2. In the /res/layout folder, we will create a simple linear layout with a single button.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:text="This is a pulsing button."
        android:id="@+id/button" />

3. Now in the /src/Main.java, modify the on create override to create a new value animator, and wire it to the background property of our button. Repeat count, repeat mode, and duration are common to all property animations. The key to our pulsing effect is the evaluator that we instantiate. You can read up on the gory details of the ArgbEvaluator in Google’s official documentation. The long and the short of it is that this nifty interpolator smoothly cycles between a start and end color value over a linear measurement of time.

package com.authorwjf.pulse;
import android.os.Bundle;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Color;
public class Main extends Activity {
    public void onCreate(Bundle savedInstanceState) {
    int start = Color.rgb(0x00, 0x99, 0x00);
    int end = Color.rgb(0x00, 0xff, 0x00);
    ValueAnimator va = ObjectAnimator.ofInt(findViewById(R.id.button), "backgroundColor", start, end);
    va.setEvaluator(new ArgbEvaluator());

Ready to give it a whirl? If so, load the resulting APK onto an emulator or device. The button background will rhythmically shift from light green to dark green and back (Figure A). Note: If you have an actual hardware device running Android 4.1 or higher, I recommend trying this demo on it. The updates to the graphics subsystem in JellyBean and beyond make the pulsing effect that much more smooth and dramatic.
Figure A