Android(min 2.1):从名称字符串加载图像

Android(min 2.1):从名称字符串加载图像,android,Android,我希望能够从res/drawable动态加载图像。我不知道会有多少个文件,但我知道它们将按约定命名为“image_N”,其中N是顺序整数。有可能在应用程序运行时上载新图像 我的代码基本上是 Resources rs = getResources(); String imgName = "android.resource://" + this.getPackageName() + "/drawable/image_" + i; int imgID = rs.getIdentifier(imgNam

我希望能够从res/drawable动态加载图像。我不知道会有多少个文件,但我知道它们将按约定命名为“image_N”,其中N是顺序整数。有可能在应用程序运行时上载新图像

我的代码基本上是

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


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

我认为您将编译的资源与文件夹中的文件弄错了。据我所知,在Android中,资源是静态的。一旦编译完毕,您就不能通过将文件放在“drawable”文件夹中来添加新资源,新文件将没有ID。 您应该在DATA中使用一个文件夹,或者最好使用GetFileDir()或类似的工具询问Android API

有关更多信息,请查看>>

我使用以下方法:

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

Drawable d = resources.getDrawable(drawableResId);
我相信你用错了。这应该起作用:

int id = Context.getResources().getIdentifier("image_" + i, "drawable", getPackageName());
这对于适配器中的id
R.drawable.image\uquot/code>是等效的

   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));
    }
语境;
公共MyAdapter0(上下文,
列表模块列表,列表模块列表2){
mInflater=LayoutInflater.from(上下文);

对于(int i=0;iBtw,正如ruhalde指出的,您不能在运行时添加可绘制资源。您必须在sd卡或内部内存上加载新图像。您好,YuviDroid-谢谢!但是您的代码基本上与我的相同,不是吗?只是看起来您遗漏了
“android:resource/”
.Ah!谢谢。如果这是真的,这会让我的事情变得更容易,也更困难。:)我放在res/drawable中的默认图像应该可以直接引用(可能通过foreach语句?)而其他的我需要浏览文件资源,或者可能是通过URL API加载。对于R.drawable中的默认图像列表,我发现了解决方案的一部分(这里)[。我的最终代码确实有这样一行代码::)谢谢!