动态设置图像/背景源

时间:2010-10-11 07:52:59

标签: android

是否有可能动态设置背景图片?!

我试着解释一下我的意思。

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

提前谢谢你,

穆尔

聚苯乙烯。 我也读过this article。在一个答案中,它会建议使用java反射按名称获取R类的字段。但我以前从未使用过反射。一个例子非常有帮助

2 个答案:

答案 0 :(得分:5)

有时我会花更多时间进行搜索:)

我找到答案为this article,对我来说效果很好:

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

答案 1 :(得分:0)

ImageView没有任何背景,但对于其他小部件(如Button),你应该使用setBackgroundResource(int)。

抱歉,我不确定我是否正确地阅读了这个问题...也许你的问题只是因为你试图将它与不使用背景的Widget一起使用?