我有一个简短的问题:
如何转换一个包含Drawable ID的字符串,即
String idString = "R.drawable.bubblegum";
到整数
idInt
这样我就可以将该ID用作图像的引用(在SimpleAdapter中使用)
因此,举个例子,我做不到:
bubble.setImageDrawable(this.getResources().getDrawable(idString));
//not possible, cause idString is a String an not an Id/Int
所以,我有包含id的String,但不幸的是,它是一个String。
谢谢!
最佳答案
尽管这个问题已经很老了,但您所缺少的是“id”和“drawable”是不同的资源类型。所以代替
getResources().getIdentifier(stringId, "id", "my.Package");
它是
getResources().getIdentifier(stringId, "drawable", "my.Package");
您还可以使用 Activity 上下文(如
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());
}
关于android - 将包含ID的字符串转换为Integer-ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8038004/