Android attr для 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 и хотел бы полностью их игнорировать, если это возможно.


person mars3142    schedule 15.04.2015    source источник


Ответы (1)


Я нашел решение для этого

@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.

person mars3142    schedule 16.04.2015