Reputation: 9255
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?
Upvotes: 1
Views: 714
Reputation: 2719
You can try
<button name="close" resLocation="@drawable/close" />
or try
ImageButton imgButton=new ImageButton(this);
imgButton.setImageResource(getResources().getDrawable(R.drawable.close));
Upvotes: 0
Reputation: 4370
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");
Upvotes: 1