如何访问具有多种格式的自定义属性?

7

我在另一个答案中看到,在Android中,您可以声明自定义视图的属性,这些属性具有多种格式,如下所示:

<attr name="textColor" format="reference|color"/>

我该如何在我的类中访问这些属性?我应该假定它是一个引用,使用getResources().getColorStateList(),然后假定它是原始的RGB/ARGB颜色,如果Resources.getColorStateList()抛出Resources.NotFoundException或者有更好的区分格式/类型的方法吗?

2个回答

3
这应该是这样的:
变体1
public MyCustomView(Context context,
                    AttributeSet attrs,
                    int defStyleAttr,
                    int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, defStyleRes);
    int resId = typed.getResourceId(R.styleable.MyCustomView_custom_attr, R.drawable.default_resourceId_could_be_color);
    Drawable drawable = getMultiColourAttr(getContext(), typed, R.styleable.MyCustomView_custom_attr, resId);
    // ...
    Button mView = new Button(getContext());
    mView.setBackground(drawable);

}

protected static Drawable getMultiColourAttr(@NonNull Context context,
                                             @NonNull TypedArray typed,
                                             int index,
                                             int resId) {
    TypedValue colorValue = new TypedValue();
    typed.getValue(index, colorValue);

    if (colorValue.type == TypedValue.TYPE_REFERENCE) {
        return ContextCompat.getDrawable(context, resId);
    } else {
        // It must be a single color
        return new ColorDrawable(colorValue.data);
    }
}

当然,getMultiColourAttr()方法可以不是静态的,也可以不是受保护的,这取决于项目。
思路是获取特定自定义属性的某些资源ID,并仅在资源不是颜色而是TypedValue.TYPE_REFERENCE时使用它,这应该意味着有Drawable需要获取。一旦获取了某个Drawable,就可以像背景一样轻松地使用它:
mView.setBackground(drawable);
变体2
通过查看变体1,您可以使用相同的resId,只需将其传递给View方法setBackgroundResource(resId),该方法将显示此资源后面的任何内容-可能是drawable或颜色。
希望这能有所帮助。谢谢

0
在你的/res/attrs.xml文件中:
<declare-styleable name="YourTheme">
    <attr name="textColor" format="reference|color"/>
</declare-styleable>

在你的自定义视图构造函数中,尝试像这样写(我没有运行它):
int defaultColor = 0xFFFFFF; // It may be anyone you want.
TypedArray attr = getTypedArray(context, attributeSet, R.styleable.YourTheme);
int textColor = attr.getColor(R.styleable.YourTheme_textColor, defaultColor);

为什么这个回答被接受了?我认为它没有回答问题。你是如何检测输入是“引用”还是“颜色”的? - lzl124631x
@Moon,getColor()方法会自动解析颜色。该方法的文档建议:检索索引处属性的颜色值。如果属性引用了一个包含复杂ColorStateList的颜色资源,则返回集合中的默认颜色。 - Flávio Faria

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接