2011-03-10 62 views
29

我有一个res/drawable-mdpi目录中的条目和一些位图文件的列表。我试图通过生成一个路径字符串并使用位图工厂来加载对应于从列表中选择的字符串值的图像。问题是我不认为我的路径是正确的,因为位图始终为空,即使对于默认图像。如何从字符串设置imageView的图像?

String name = entries.get(position); 
      String img = "res/drawable/logo_" + name.toLowerCase() + ".png"; // create the file name 
      icon.setScaleType(ImageView.ScaleType.CENTER_CROP); 

      // check to see if the file exists 
      File file = new File(img); 
      if (file.exists()){ 

       bm = BitmapFactory.decodeFile(img); 
      } 
      else{// use the default icon 
       bm = BitmapFactory.decodeFile("logo_default.png"); 
      } 

      // set the image and text 
      icon.setImageBitmap(bm); 

res目录是否被拷贝到设备上?什么是我应该使用的正确途径,还是应该以不同的方式来解决这个问题?

感谢

如果你有你要对这个错误的方式绘制文件夹中的图像
+1

你应该阅读有关程序如何处理的Android资源:HTTP:// developer.android.com/guide/topics/resources/index.html – WarrenFaith 2011-03-10 00:40:01

+0

谢谢,这解释了很多。 – Matt 2011-03-10 00:52:49

回答

46

尝试这样的事情

Resources res = getResources(); 
String mDrawableName = "logo_default"; 
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName()); 
Drawable drawable = res.getDrawable(resID); 
icon.setImageDrawable(drawable); 
+2

'getDrawable()'被删除。 – 2015-12-29 09:27:04

+1

尝试Drawable drawable = ContextCompat.getDrawable(getContext(),resID); – 2017-02-22 14:27:46

12

无需使用getDrawable()你直接使用资源ID喜欢

String mDrawableName = "myimageName"; int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName()); imgView.setImageResource(resID);

相关问题