tos
tos

Reputation: 996

Accessing application resources from the library project

My application depends on a library project.

The menu.xml file is within the application project.
All the java code is within the library project, including the menu handler code onOptionsItemSelected().

Is there a way to access the application resources from library project ? I'd like to write something like this, which is currently impossible, since menu items are not visible from the library:

if ( item.getItemId()==R.id.settings ) {
...
}

Upvotes: 14

Views: 14175

Answers (3)

triad
triad

Reputation: 21497

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");

Upvotes: 23

medavox
medavox

Reputation: 306

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.

Upvotes: 1

kabuko
kabuko

Reputation: 36302

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.

Upvotes: 13

Related Questions