开发者

Set image / background source dynamically

开发者 https://www.devze.com 2023-01-19 06:24 出处:网络
is there any possibility to set background image dynamically?! I try to explain what I mean. String picVariable = getPictureFromServer();

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 开发者_如何学Pythonsuggested 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


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);


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 ?

0

精彩评论

暂无评论...
验证码 换一张
取 消