0

I have a custom progress bar used around the app which has a attribute for setting the indeterminate color. Since I am using the support library I am trying to have the progress bar colored on older android versions too.

In attrs I have something like:

<declare-styleable name="TestView">
        <attr name="testColor" format="color"/>
</declare-styleable>

When declaring the view:

<com.TestView
  ....
  app:testColor="#color"
/>

Then my custom view is like this:

public class TestView extends ProgressBar {

    public TestView(Context context) {
        super(context);
        applyTint(Color.WHITE);
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TestView, 0, 0);

        try {
            applyTint(attributes.getColor(R.styleable.TestView_testColor, Color.WHITE));
        } finally {
            attributes.recycle();
        }

    }

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, android.support.design.R.style.Base_Widget_AppCompat_ProgressBar);
        TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TestView, 0, 0);

        try {
            applyTint(attributes.getColor(R.styleable.TestView_testColor, Color.WHITE));
        } finally {
            attributes.recycle();
        }
    }

    private void applyTint(int color) {
        if (Build.VERSION.SDK_INT >= 21) {
            setIndeterminateTintList(ColorStateList.valueOf(color));
        } else {
            getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
        }
    }
}

The problem I have is that it seems that the attribute of color is somehow shared between instances of TestView. How can I have each view to keep its own attribute value?

Later edit: seems to work fine on android 6 but fails on 4.4.2

Alin
  • 14,809
  • 40
  • 129
  • 218

1 Answers1

0

Got the answer at https://stackoverflow.com/a/37434219/379865

Basically I had to update my tint apply code with:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   DrawableCompat.setTint(DrawableCompat.wrap(getIndeterminateDrawable()), color);
else {
   DrawableCompat.wrap(getIndeterminateDrawable()).mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Community
  • 1
  • 1
Alin
  • 14,809
  • 40
  • 129
  • 218