这应该是这样的:
变体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 {
return new ColorDrawable(colorValue.data);
}
}
当然,getMultiColourAttr()方法可以不是静态的,也可以不是受保护的,这取决于项目。
思路是获取特定自定义属性的某些资源ID,并仅在资源不是颜色而是TypedValue.TYPE_REFERENCE时使用它,这应该意味着有Drawable需要获取。一旦获取了某个Drawable,就可以像背景一样轻松地使用它:
mView.setBackground(drawable);
变体2
通过查看变体1,您可以使用相同的resId,只需将其传递给View方法setBackgroundResource(resId),该方法将显示此资源后面的任何内容-可能是drawable或颜色。
希望这能有所帮助。谢谢
getColor()
方法会自动解析颜色。该方法的文档建议:检索索引处属性的颜色值。如果属性引用了一个包含复杂ColorStateList的颜色资源,则返回集合中的默认颜色。 - Flávio Faria