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

Gri*_*u47 6 android attributes custom-view

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

<attr name="textColor" format="reference|color"/>
Run Code Online (Sandbox Code Playgroud)

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

Sto*_*eev 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当然 getMultiColourAttr() 方法可以不是静态的并且不受保护,这取决于项目。

这个想法是为这个特定的自定义属性获取一些resourceId,并且仅当资源不是颜色而是TypedValue.TYPE_REFERENCE时才使用它,这应该意味着可以获取Drawable。一旦你得到一些 Drawable 应该很容易使用它,例如背景:

mView.setBackground(drawable);

变体2

看看变体 1,您可以使用相同的resId,但只需将其传递给 View 方法 setBackgroundResource(resId),该方法将仅显示此资源后面的任何内容 - 可以是可绘制的或颜色的。

我希望它会有所帮助。谢谢