Skip to content

Instantly share code, notes, and snippets.

@NightlyNexus
Created April 1, 2015 02:28
Show Gist options
  • Save NightlyNexus/cca0e2703fbe14525473 to your computer and use it in GitHub Desktop.
Save NightlyNexus/cca0e2703fbe14525473 to your computer and use it in GitHub Desktop.
TintedProgressBar
<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="TintedProgressBar">
<attr name="tint" format="color|reference" />
</declare-styleable>
<?xml version="1.0" encoding="utf-8"?>
<com.ifttt.lib.TintedProgressBar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:indeterminate="true"
app:tint="@color/ifttt_blue_light" />
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ProgressBar;
public class TintedProgressBar extends ProgressBar {
public TintedProgressBar(Context context) {
super(context);
init(context, null, 0);
}
public TintedProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public TintedProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TintedProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TintedProgressBar, defStyle, 0);
if (a == null) {
return;
}
if (a.hasValue(R.styleable.TintedProgressBar_tint)) {
final int tintColor = a.getColor(R.styleable.TintedProgressBar_tint, 0);
getIndeterminateDrawable().setColorFilter(tintColor, PorterDuff.Mode.SRC_IN);
getProgressDrawable().setColorFilter(tintColor, PorterDuff.Mode.SRC_IN);
}
a.recycle();
}
}
@StefMa
Copy link

StefMa commented Oct 21, 2016

When we use the TintedProgressBar and AppCompat 23.4.0 with style="@style/Widget.AppCompat.ProgressBar" (instead of Widget.AppCompat.ProgressBar. Horizontal) it will crash.
Why? Because getProgressDrawable() or getIndeterminateDrawable() can be null.

Fix:

final Drawable progressDrawable = getProgressDrawable();
if (progressDrawable != null) {
    progressDrawable.setColorFilter(tintColor, PorterDuff.Mode.SRC_IN);
}
final Drawable indeterminateDrawable = getIndeterminateDrawable();
if (indeterminateDrawable != null) {
    indeterminateDrawable.setColorFilter(tintColor, PorterDuff.Mode.SRC_IN);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment