如何根据字符串变量按名称获取资源?

时间:2012-05-31 20:40:03

标签: android

我想做

String childImg = "childIcon";
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.????, 0, 0, 0);

它期待一个int,但我有一个字符串。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:3)

我用它来获得drawable id

getResources().getIdentifier(childImg, "drawable", getPackageName())

答案 1 :(得分:1)

使用getIdentifier()

int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());

答案 2 :(得分:1)

这样做:

String childImg = "childIcon";
int id = getResources().getIdentifier(childImg, "drawable", getPackageName())
textView.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0);

答案 3 :(得分:0)

textView.setCompoundDrawablesWithIntrinsicBounds(Resources.getIdentifier(childImg), 0, 0, 0);