2012-10-28 52 views
0

String imagename =“mypicture”;Android从字符串设置图像

 ImageView lblPic = new ImageView(this); 
     int resID = getResources().getIdentifier(imagename, "drawable", getPackageName()); 
     lblPic.setImageResource(resID); 

这是我的xml文件。

<ImageView android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:id="@+id/image1" android:src="@drawable/no_image" /> 

哪里有问题?我认为ive安装xml文件错误..?我已经尝试了很多代码,但每次Java代码都不会改变图片,它仍然保留在xml文件中。

回答

1

正确:

<ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/image1" 
      android:src="@drawable/no_image" /> 

把这行放到你的活动onCreate方法:

ImageView lblPic = (ImageView) findViewById(R.id.image1); 
int resID = getResources().getIdentifier(imagename, "drawable", getPackageName()); 
lblPic.setImageResource(resID); 
+1

感谢。我发现我必须使用文件名,而不需要扩展名:) – coldwind