Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

android - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...