Android - getIdentifier总是返回0(库+应用程序)

blu*_*zcz 17 resources android

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

我想要做的是获取图片库的资源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");
Run Code Online (Sandbox Code Playgroud)

编辑:

Ach,在R.java中有drawable和corensponding属性.

小智 32

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


Ted*_*opp 30

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

resId = getResources().getIdentifier("fr_200_133", "drawable", getPackageName());
Run Code Online (Sandbox Code Playgroud)

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

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

  • @bluszcz - 我想我从某个地方的例子中找到了这个成语.关键是您需要使用应用程序的程序包名称(如清单中所列)而不是库的程序包名称(在创建应用程序时实际上会消失). (2认同)

Jos*_*ter 11

我得到了同样的错误,唯一有用的是以不同的方式进行:

resourceId = R.drawable.class.getField("fr_200_133").getInt(null);
Run Code Online (Sandbox Code Playgroud)

  • @MalwinderSingh 你能解释一下为什么吗? (2认同)

小智 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());
Run Code Online (Sandbox Code Playgroud)