Tima
Tima

Reputation: 12905

Set image / background source dynamically

is there any possibility to set background image dynamically?!

I try to explain what I mean.

String picVariable = getPictureFromServer();

ImageView image = (ImageView)v.findViewById(R.id.dynamic_image);

// I know, that doesn't work, but that's the way I looking for
image.setBackgroundResource(picVariable); 

Thank you in advance,

Mur

Ps. I also read this article. It would suggested in one answer, to use java reflection to get a field of the R class by name. But I've never used reflextion before. An example would be very helpfull

Upvotes: 1

Views: 11614

Answers (2)

Tima
Tima

Reputation: 12905

Sometimes I should take a bit more time for searching :)

I found the answer reading this article, and it works fine for me:

// The server says, it should be *.png
String picName = getPictureFromServer();
picName = picName.replace(".png", "");

Resources r = getResources();
int picId = r.getIdentifier(picName, "drawable", "com.mypackage.myapp");

ImageView image = (ImageView)v.findViewById(R.id.dynamic_image);
image.setBackgroundResource(picId);

Upvotes: 5

Matthieu
Matthieu

Reputation: 16397

ImageView does not have any background, but for other widget (like Button), you should use setBackgroundResource(int).

Sorry, I am not sure I read the question correctly... maybe your problem is just that you are trying to use it with a Widget that does not use background ?

Upvotes: 0

Related Questions