以下是我的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();
}
}
但是它抛出如下错误信息
Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x1 at android.content.res.TypedArray.getColor(TypedArray.java:339)
我怎样才能解决这个问题?
最佳答案
来自源代码here
* @throws UnsupportedOperationException 如果定义了属性但是
* 不是整数颜色或颜色状态列表。
改变颜色值:
selectedIndicatorPaint.setColor(typedArray.getColor(R.styleable.MaterialIndicator_mi_indicatorColor, 0));
从零到颜色值。其中颜色值是:
颜色
在 XML 中定义的颜色值。颜色由 RGB 值和 alpha channel 指定。您可以在任何接受十六进制颜色值的地方使用颜色资源。当 XML 中需要可绘制资源时,您还可以使用颜色资源(例如,android:drawable="@color/green")。
https://developer.android.com/guide/topics/resources/more-resources.html#Color
编辑:像 #80ff0000
这样的东西应该可以工作
关于android - 无法在自定义 View 中使用 typedarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39717313/