简体   繁体   English

可绘制资源的Android动态变量

[英]Android dynamic variable for drawable resource

Hi I have a problem for my coding, how can I do this: 嗨,我的编码有问题,该怎么做:

BitmapFactory.decodeResource(getResources(), R.drawable."some string");

I'm using: 我正在使用:

getResources().getIdentifier(img, "drawable", context.getPackageName()) , getResources().getIdentifier(img, "drawable", context.getPackageName())

then it's showing: 然后显示:

error cannot resolve method decodeResource(int) 错误无法解决方法encodeResource(int)

Technically you can't do it that way, because "R.drawable.XXXXX" is an int that is generated at compile time. 从技术上讲,您不能那样做,因为“ R.drawable.XXXXX”是在编译时生成的int。 I would recommend making a custom enum that associates the int with the string and provides a method to return one given the other. 我建议创建一个自定义枚举,该枚举将int与字符串相关联,并提供一种返回给定另一个的方法。 For example: 例如:

public enum DrawableEnum {
    STRING_ONE("some string", R.drawable.some_string),
    STRING_TWO("another string", R.drawable.some_other_string),
    STRING_THREE("third string", R.drawable.string_three);

    private final String string;
    private final int resId;

    DrawableEnum(String string, int resId) {
        this.string = string;
        this.resId = resId;
    }

    int getResId() {
        return resId;
    }

    String getString() {
        return string;
    }

    int getResIdFromString(String string) {
        for(DrawableEnum item : DrawableEnum.values()) {
            if(item.getString().equals(string)) {
                return item.getResId();
            }
        }
        return -1;
    }
}

Then call it like this: 然后这样称呼它:

int resId = DrawableEnum.getResIdFromString("some string");
BitmapFactory.decodeResource(getResources(), resId);

You will be able to get resource id with the following code: 您将可以使用以下代码获取资源ID:

int resId = getResources().getIdentifier("some_string", "drawable", getPackageName());
BitmapFactory.decodeResource(getResources(), resId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM