应该是这样的:
变体 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() 方法可以不是静态的并且不受保护,这取决于项目。
思路是为这个特定的自定义属性获取一些resourceId,并且只有在资源不是color而是TypedValue.TYPE_REFERENCE的情况下才使用它,这应该意味着有Drawable可以获取。一旦你得到一些 Drawable 应该很容易使用它,例如背景:
mView.setBackground(drawable);
变体 2
查看变体 1,您可以使用相同的 resId,但只需将其传递给 View 方法 setBackgroundResource(resId),该方法将仅显示该资源后面的任何内容 - 可以是可绘制的或颜色的。
我希望它会有所帮助。谢谢