android - 无法在自定义 View 中使用 typedarray

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

但是它抛出如下错误信息

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/

相关文章:

Android:带有 GridLayoutManager 的 RecyclerView 中的 Picasso 图像

java - 在模拟器中打开时 Android 代码崩溃

java - java接收数据后无法将string转换为int

javascript - 如何使用 webgl 处理和更新大型数组?

android - 拥有版本代码为 1 的 APK(目标 SDK 23 或更高版本)的用户

Android 双指缩放ImageView(PhotoView)与ScrollView

javascript - 将二进制 ArrayBuffer/TypedArray 数据转换为十六进制字符串

javascript - 在字符串和 ArrayBuffers 之间转换

javascript - 在 Javascript 中将字符串转换为类型化数组

javascript - 复制 ArrayBuffer 对象最直接的方法是什么?