Android 属性到 xml 个可绘制对象

Android attr to xml drawables

TL;DR 我正在寻找 public static Drawable getDrawableFromAttribute(Context context, String attrName).

的实现

我正在寻找一种方法来加载动态可绘制对象,它们是在我的样式中使用自定义属性定义的。这是我的配置

attr.xml

<resources>
   <attr name="custom_image" type="reference">
</resources>

styles.xml

<resources>
   <style name="demo">
      <item name="custom_image">@drawable/fancy_picture</item>
   </style>
</resources>

fancy_picture是一个命名为/res/drawables/fancy_pictures.xml.

现在,我希望有人输入字符串 "custom" 和 "image",ImageView 应该在其中显示 fancy_picture。

最好的方法是什么?如果我使用 XML-Layout 文件,我可以写

<ImageView
    ...
    android:src="?custom_image"
    ...
    />

我没有在我的风格中使用 declare-styleable xml,如果可能的话,我想完全忽略它们。

我找到了解决方案

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Drawable getAttrDrawable(Context context, @AttrRes int attrRes) {
    Drawable drawable = null;
    TypedValue value = new TypedValue();
    if (context.getTheme().resolveAttribute(attrRes, value, true)) {
        String[] data = String.valueOf(value.string).split("/");
        int resId = context.getResources().getIdentifier(data[2].substring(0, data[2].length() - 4), "drawable", context.getPackageName());
        if (resId != 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                drawable = context.getDrawable(resId);
            } else {
                drawable = context.getResources().getDrawable(resId);
            }
        }
    }
    return drawable;
}

public static Drawable getAttrDrawable(Context context, String attr) {
    int attrRes = context.getResources().getIdentifier(attr, "attr", context.getPackageName());
    if (attrRes != 0) {
        return getAttrDrawable(context, attrRes);
    }
    return null;
}

它对 attr -> xml 和 attr -> png 效果很好。