Coloring a ProgressBar on Android

On newer versions of Android (such as Lollipop and Marshmallow) the activity indicator now has a distinct color instead of just being a shade of gray. While this is neat, it brings up the potential for the color of the activity indicator to clash with your design.

Fortunately it is possible to change the color of these controls. Starting with the xml in the layout, your progress bar will look as follows…

<ProgressBar
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:id="@+id/activityIndicator"
    android:progressDrawable="@drawable/colorProgress"
    android:indeterminateOnly="true"/>

The relevant part of this code is the setting of progressDrawable to a custom drawable object. While this custom object must exist, it doesn’t actually have to do anything. The full source of colorProgress.xml is below and is essentially blank.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
</selector>

Finally we will get to the Java code that actually sets the color of the progress bar. This is done as the program starts up and consists of three steps. First, you filter out the older Android OS versions to avoid crashing the app on Android 4.x phones. Next you get a reference to the ProgressBar object, and then finally you set the object to the color you want.

protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
ProgressBar progressbar = (ProgressBar) findViewById(R.id.activityIndicator);
int color = 0xFF2980b9;
progressbar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
progressbar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
}