Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing resources in module

I've create a module at Android Studio. In module code, I want to show a dialog which uses a layout defined in the module. When I reference layout like net.gwtr.module.R.layout.my_dialog_layout, I get this exception;

java.lang.ClassNotFoundException: Didn't find class "net.gwtr.module.R$layout" on path: DexPathList[[zip file "/data/app/net.gwtr.moduletest-1.apk"],nativeLibraryDirectories=[/data/app-lib/net.gwtr.moduletest-1, /vendor/lib, /system/lib]]

I think the reason is that resources are merged when you add a module to project. It did not create different resource ids for the module package name. So i cannot reach to resources from module package.

How can I reference resources of module in module code?

Edit1: I reference resource like this;

Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.my_dialog_layout);
dialog.show();

Edit2: I found a way but i don't want to use this every time when I reference resource.

I can reach resources when I get resource id with this;

context.getResources().getIdentifier("my_dialog_layout", "layout", context.getPackageName())
like image 498
ferpar1988 Avatar asked Aug 21 '14 08:08

ferpar1988


3 Answers

I had to add the package name for the resource, e.g. instead of R.drawable.icon, I needed com.example.brand.module_name.R.drawable.icon

like image 181
Ben Butterworth Avatar answered Sep 24 '22 19:09

Ben Butterworth


In your gradle file from your module.

Are you put compile your other module?

compile project(':othermodule')
like image 4
joselufo Avatar answered Oct 08 '22 14:10

joselufo


Yes, resources from libraries are merged into your application (so basically there's a global namespace under R; this is why you have to choose resource names in modules with a little care, e.g. use a prefix, to prevent accidental mix-up with resources from other modules).

Within the defining library module, and your application module by virtue of the resource merging, you should just be able to refer to R.layout.my_dialog_layout (android studio should auto-complete). I've a similar situation working fine in my project (@jimpanzer: I tried under same versions as you, with compileSdkVersion = 16 and 20).

Some suggestions:

  • make sure there are no import statements of R anywhere. As far as I can see you shouldn't need any, if you either address library resources from your application module, or from the same library module.

  • clean your project and rebuild, perhaps even android studio caches. In the old days, sometimes R.java would get screwed up.

like image 3
Dion Avatar answered Oct 08 '22 14:10

Dion