Search code examples
androidtyped-arrays

Unable to use typedarray in a custom view


Following is my styelable.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <declare-styleable name="MaterialIndicator">
    <attr name="mi_indicatorRadius" format="dimension|reference" />
    <attr name="mi_indicatorPadding" format="dimension|reference" />
    <attr name="mi_indicatorColor" format="color|reference" />
  </declare-styleable>

</resources>

Im referring the above styelable as follows,

public MaterialIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        selectedIndicatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        indicatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        indicatorPaint.setColor(Color.BLACK);
        indicatorPaint.setAlpha((int) (deselectedAlpha * 255));
        selectorRect = new RectF();
        if (isInEditMode()) {
            count = 3;
        }
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaterialIndicator, 0, R.style.MaterialIndicator);
        try {
           selectedIndicatorPaint.setColor(typedArray.getColor(R.styleable.MaterialIndicator_mi_indicatorColor, 0));
        } finally {
            typedArray.recycle();
        }
    }

But it throws the following error message

Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x1 at android.content.res.TypedArray.getColor(TypedArray.java:339)

how can i be able to sort this out?


Solution

  • From the source code here

    * @throws UnsupportedOperationException if the attribute is defined but is * not an integer color or color state list.

    Change color value :

               selectedIndicatorPaint.setColor(typedArray.getColor(R.styleable.MaterialIndicator_mi_indicatorColor, 0));
    

    from zero to a color value. Where color value is :

    Color A color value defined in XML. The color is specified with an RGB value and alpha channel. You can use a color resource any place that accepts a hexadecimal color value. You can also use a color resource when a drawable resource is expected in XML (for example, android:drawable="@color/green").

    https://developer.android.com/guide/topics/resources/more-resources.html#Color

    Edit : Something like #80ff0000 should work