18

我有使用 Android 库 (com.appocaliptic.quizknife.core) 的 Android 项目 (com.appocaliptic.quizknife.app)。

我想要做的是获取图片的资源ID,即图书馆。图片的路径是:res/drawable-xhdpi/fr_200_133.png

但是,所有尝试都使用 getIdentifier 结果为 0。问题出在哪里?

resId = getResources().getIdentifier("fr_200_133", "drawable", "com.appocaliptic.quizknife.core");
resId = getResources().getIdentifier("com.appocaliptic.quizknife.core:drawable/"+"fr_200_133", null, null);
resId = getResources().getIdentifier("drawable/fr_200_133", null, "com.appocaliptic.quizknife.core");

编辑:

啊,在 R.java 中有可绘制和对应的属性。

4

5 回答 5

38

我遇到了同样的问题:“getIdentifier result 0”,我通过删除图像扩展名(*.jpg、*.jpeg、...等)以匹配R.java文件中的名称来解决它

于 2013-03-07T09:08:46.087 回答
33

您不应该使用库包名称。试试这个:

resId = getResources().getIdentifier("fr_200_133", "drawable", getPackageName());

(或者getContext().getPackageName()如果这是在视图中执行)。

关键是您需要使用应用程序的包名(如清单中所列)而不是库的包名(在创建应用程序时实际上会消失)。

于 2012-09-12T20:23:18.920 回答
12

我遇到了同样的错误,唯一有效的方法是以不同的方式解决它:

resourceId = R.drawable.class.getField("fr_200_133").getInt(null);
于 2013-12-12T05:56:08.500 回答
8

我有一个类似的问题。我可以像 Hussam Otri 提到的那样解决它。例如:

//This doesn't work
context.getResources().getIdentifier("audio_1.mp3", "raw", this.getPackageName()); 

//This works (strip off the file extension)
context.getResources().getIdentifier("audio_1", "raw", this.getPackageName());
于 2017-08-05T13:10:42.507 回答
0

图像的名称是下划线(下划线)或“_”,结果没问题,因为编译器将照片的名称重命名为示例:源:“img0001”在编译“imag_0001”后。

于 2018-10-24T10:42:23.577 回答