Link to resources in the module

I created a module in Android Studio. In the module code, I want to show a dialog that uses the layout defined in the module. When I reference a layout, for example 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 the resources are combined when adding a module to the project. He did not create different resource identifiers for the module package name. Therefore, I cannot get to the resources from the module package.

How can I refer to module resources in a module?

Edit1: I reference the resource as follows:

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

Edit2: I found a way, but I do not want to use it every time I refer to a resource.

I can get resources when I get the resource identifier with this;

 context.getResources().getIdentifier("my_dialog_layout", "layout", context.getPackageName()) 
+5
source share
4 answers

In your gradle file from your module.

Are you going to compile your other module?

 compile project(':othermodule') 
+4
source

Yes, resources from libraries are integrated into your application (so basically there is a global namespace under R, so you need to choose resource names in modules with a little care, for example, use a prefix to prevent accidental mixing with resources from other modules).

Inside the defining library module and your application module, due to the merging of resources, you should just be able to reference R.layout.my_dialog_layout (Android studio should automatically populate). I have a similar situation in my project (@jimpanzer: I tried in the same versions as you, with compileSdkVersion = 16 and 20).

Some suggestions:

  • make sure that it does not have import statements R. As far as I can see, you do not need anything if you are either accessing library resources from your application module or from the same library module.

  • clean your project and rebuild, perhaps even Android sneakers. In the old days, sometimes Rzhava would have been bolted.

+2
source

import net.gwtr.module.R.* and access the layout via getResources() as before

+1
source

I convert the old project to Android studio and get package names mixed in the module. Although the R file was created, it was in the wrong package.

In the module, check the file mapping the resource to file

build-> generate / source-> debug → (application package) → R

or

build-> generated / source-> release → (application package) → R

The package of this file must match the import of R eg in your activity

+1
source

Source: https://habr.com/ru/post/1200813/


All Articles