Le Parkour
Le Parkour

Reputation: 97

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()),

then it's showing:

error cannot resolve method decodeResource(int)

Upvotes: 1

Views: 340

Answers (2)

t-kashima
t-kashima

Reputation: 271

You will be able to get resource id with the following code:

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

Upvotes: 0

var47
var47

Reputation: 440

Technically you can't do it that way, because "R.drawable.XXXXX" is an int that is generated at compile time. I would recommend making a custom enum that associates the int with the string and provides a method to return one given the other. 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);

Upvotes: 2

Related Questions