10ff
10ff

Reputation: 813

Convert String containing an ID into an Integer-ID

I have a short question:

How is it possible to convert a String, containing the Id of a Drawable, which is

String idString = "R.drawable.bubblegum";

to an Integer,

idInt

so that I can use that ID for the reference of an image (, which is used in a SimpleAdapter)

So, to make an example, I can't do that:

bubble.setImageDrawable(this.getResources().getDrawable(idString));
//not possible, cause idString is a String an not an Id/Int

So, I have the String that's containing the id, but unfortunately as a String.

Thanks!

Upvotes: 14

Views: 19257

Answers (6)

user3793638
user3793638

Reputation: 31

You could try the following

int id = getResources().getIdentifier("arr_name"+positionSelected,
                        "array", rootview.getContext().getPackageName());

I use in spinner dropdown, get array string follow parent spinner may help you!

Upvotes: 3

domsom
domsom

Reputation: 3171

Although this question is rather old already, the thing you're missing is that "id" and "drawable" are different resource types. So instead of

getResources().getIdentifier(stringId, "id", "my.Package");

it's

getResources().getIdentifier(stringId, "drawable", "my.Package");

You can also get package name with the activity context like activityContext.getPackageName()

/**
 * Returns Identifier of String into it's ID as defined in R.java file.
 * @param pContext
 * @param pString defnied in Strings.xml resource name e.g: action_item_help
 * @return
 */
public static int getStringIdentifier(Context pContext, String pString){
    return pContext.getResources().getIdentifier(pString, "string", pContext.getPackageName());
}

Upvotes: 22

10ff
10ff

Reputation: 813

At least, I couldn't get a solution for this problem. It seems that there's no way to convert a String "R.id.mytext" into an integer like R.id.mytext that can be used in findViewById(R.id.myText).

Upvotes: -2

Vladimir
Vladimir

Reputation: 9753

if your idString is constant, i.e. it's doesn't change during runtime, follow DeeV's answer. If it changes, you can take a look at getIdentifier method.

Upvotes: 0

DeeV
DeeV

Reputation: 36045

int idInt = R.drawable.bubblegum;

Unless there's something I'm missing here.

Upvotes: 0

Related Questions