Accessing application resources from the library project

You should really just include a version of the menu.xml resource in your library project. If you want to have a different menu.xml in your application, you can do that and it will override the copy from the library project.

From the Library Projects docs:

In cases where a resource ID is defined in both the application and the library, the tools ensure that the resource declared in the application gets priority and that the resource in the library project is not compiled into the application .apk. This gives your application the flexibility to either use or redefine any resource behaviors or values that are defined in any library.


I found @triad's solution with Resources.getIdentifier(String, String, String) to be somewhat error-prone:

  • the String-literal resource identifiers aren't checked by the IDE
  • multiple sequential String arguments to a single method are easy to use incorrectly.

I found this approach to work better for me:

String libString = context.getString(example.library.pkg.R.string.library_string)

Where the library's package is example.library.pkg.

  • The library's R class is resolved at compile-time, so your IDE will tell you if you referenced it correctly
  • Not importing the library's R class allows you to still use your own local R later, and explicitly marking the external resource usages makes them easier to spot.

Yes you can if you know the package name of your library. See: Resources#getIdentifier

You can do:

getResources().getIdentifier("res_name", "res_type", "com.library.package");

ex:

R.id.settings would be:

getResources().getIdentifier("settings", "id", "com.library.package");

Tags:

Android