1

I have an xml file that specifies a set of image button names. Also, I would like to specify the image resource id as an attribute of an xml node as shown below:

<button name="close" resLocation="R.drawable.close" />

I am parsing the xml in the code, I would like to set the image background for the dynamically created button using the resLocation attribute. Since resLocation is a string, I cannot convert to a Drawable object directly. Is there a way I can workaround?

ssk
  • 9,045
  • 26
  • 96
  • 169

2 Answers2

1

You can use get getResources().getIdentifier:

String myResourceId = "close"; // Parsed from XML in your case
getResources().getIdentifier(myResourceId, "drawable", "com.my.package.name");

This would require your XML to be a little different:

<button name="close" resLocation="close" />

If you need to keep the R.type.id format in your XML, then you would just need to parse out the type and id:

String myResourceId = "R.drawable.close";
String[] resourceParts = myResourceId.split("\\.");
getResources().getIdentifier(resourceParts[2], resourceParts[1], "com.my.package.name");
goto10
  • 4,370
  • 1
  • 22
  • 33
0

You can try

<button name="close" resLocation="@drawable/close" />

or try

ImageButton imgButton=new ImageButton(this);

imgButton.setImageResource(getResources().getDrawable(R.drawable.close));
Mahendran
  • 2,719
  • 5
  • 28
  • 50
  • This won't work because the resource identifiers are being read from an XML file (not a layout file) and will only be available as strings. – goto10 Oct 23 '11 at 06:57
  • Sorry for the misunderstand the question ..You could refer [link]http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string[/link] – Mahendran Oct 23 '11 at 07:01
  • 1
    You could use reflection, but `getIdentifier` is the more clear way to do it and it's provided by the API so it's the sanctioned method for getting a resource from a string. The answer in that link even includes an edit that the author wasn't aware of `getIdentifier` at the time he answered. – goto10 Oct 23 '11 at 07:05