0

Possible Duplicate:
Setting Android images from string value

I need to change background image programmatically on Android with source string I have. For example I have an array of strings gotten from XML file "source1", "source2" etc., so how can I set them to background as images? I saw examples like mTextView.setBackgroundResource(R.drawable.myResouce);, but I don't understand how to set mySource from a String. May be it is possible through drawable object?

3
  • see stackoverflow.com/questions/4313007/… Commented Apr 18, 2012 at 10:55
  • Why you make text as a background..? If you need hint then use "android:hint"... Commented Apr 18, 2012 at 10:57
  • Which type of strings are you getting from XML file? Can you show some examples? Commented Apr 18, 2012 at 11:04

1 Answer 1

5

Keep your images name inside drawables same as of in String.xml.

Say for eg: images.png it should be images in String.xml

If you pass this name to getResourceId() it will returns you Drawable with that String Variable.

public static int getResourceId(Context context, String name, String resourceType) {
    return context.getResources().getIdentifier(name, resourceType, context.getPackageName());
}

int iconId = getResourceId(Activity.this, image, "drawable");    

ImageView categoryIcon = (ImageView) v.findViewById(R.id.category_icon);
categoryIcon.setImageResource(iconId);
Sign up to request clarification or add additional context in comments.

7 Comments

What is toResourceString(name) method?
Check mu updated answer.No need of that method..Simply pass String name
I've tried this, but it didnt work for me View v = new View(this); TextView textView = (TextView) v.findViewById(R.id.provider_logo); int resid = Helpers.getResourceId(PaymentActivity.this, "logo", "drawable"); textView.setBackgroundResource(resid);`
You have to set Background for ImageView, why are you setting for TextView?
Yeap, works good without v in v.findViewById - answer accepted =)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.