无法在自定义视图中使用typedarray

时间:2016-09-27 06:17:13

标签: android typed-arrays

以下是我的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>

我指的是上面提到的,如下,

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();
        }
    }

但它会抛出以下错误消息

  

引起:java.lang.UnsupportedOperationException:无法转换为   color:type = 0x1                                                                                                      在android.content.res.TypedArray.getColor(TypedArray.java:339)

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

来自源代码here

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

更改颜色值:

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

从零到颜色值。颜色值是:

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

编辑:#80ff0000之类的内容应该有效