2012-03-05 55 views
1

我希望能够从res/drawable动态加载图像。我不会有多少文件,但我知道它们将按照惯例命名为“image_N”,其中N是顺序整数。在应用程序运行时可能会上传新图像。Android(min 2.1):从名称字符串中加载图像

我的代码基本上是

Resources rs = getResources(); 
String imgName = "android.resource://" + this.getPackageName() + "/drawable/image_" + i; 
int imgID = rs.getIdentifier(imgName , null, getPackageName()); 

if (imgID != 0) 
{ 
    Drawable d = rs.getDrawable(imgID); 
    //etc. 
} 

imgID返回总是0

我也尝试另一种方法

String imgName = "android.resource://" + this.getPackageName() + "/drawable/image_" + i; 
b = BitmapFactory.decodeFile(imgName); 
if (b != null) 
//etc 

b总是null

我知道文件夹中有正确的名称,因为我在那里放了几个。不知道我做错了什么。任何帮助将不胜感激!

回答

0

我想你已经错误地编译了资源文件夹内的文件。在Android中,据我所知,资源是静态的。编译完成后,您无法通过在“drawable”文件夹中删除文件来添加新资源,因此新文件不会有ID。 你应该在DATA中使用一个文件夹,或者更好地用getFilesDir()或类似的东西来询问Android API。

欲了解更多信息,请查看>>here

+0

啊!谢谢。如果那是真的,它会让事情变得更容易和更难。 :)我放在res/drawable中的默认图像应该可以直接引用(也许通过foreach语句?),而其他的我需要通过文件资源 - 或者通过URL API加载。 – 2012-03-06 01:48:02

+0

对于R.drawable中图像的默认列表,我发现解决方案的一部分(这里)[http://stackoverflow.com/a/3950277/1181368]。 – 2012-03-06 03:33:16

0

我用这个:

String drawableName = "drawableNameAsDeclaredInDrawableDir" // in your case "image_" + i; 
int drawableResId = resources.getIdentifier(packageName + ":drawable/" + drawableName, null, null); 

然后使用

Drawable d = resources.getDrawable(drawableResId); 
+0

顺便说一句,ruhalde指出你不能在运行时添加可绘制的资源。您将不得不在SD卡或内存上加载新图像。 – YuviDroid 2012-03-06 00:08:02

+0

Hi YuviDroid - 谢谢!但是你的代码与我的基本相同,不是吗?除了看起来你忘了''android:resource //“'。 – 2012-03-06 01:44:56

2

我相信你正在使用getIdentifier(...)不正确。这应该工作:

int id = Context.getResources().getIdentifier("image_" + i, "drawable", getPackageName()); 

这将是equivilent在适配器的ID R.drawable.image_<+i>

+0

我的最终代码确实有一条看起来像这样的线。 :) 谢谢! – 2012-03-06 03:41:28

0

我用这个

Context context; 
    public MyAdapter0(Context context, 
    List<String> moduleList,List<String> moduleList2) { 
    mInflater = LayoutInflater.from(context); 
    for (int i=0;i<moduleList.size();i++) { 
    int id = context.getResources().getIdentifier("color6_"+i, 
    "drawable", context.getPackageName()); 
    mItems.add(new Item(moduleList.get(i),moduleList2.get(i),id)); 
    // Log.d("idimage", String.valueOf(R.drawable.color6)); 
    }