Accessing application resources from the library project

前端 未结 3 1952
误落风尘
误落风尘 2020-12-06 01:23

My application depends on a library project.

The menu.xml file is within the application project.
All the java code is within the library projec

相关标签:
3条回答
  • 2020-12-06 02:17

    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.
    0 讨论(0)
  • 2020-12-06 02:21

    Yes you can if you know the package name of your library.
    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");

    0 讨论(0)
  • 2020-12-06 02:27

    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.

    0 讨论(0)
提交回复
热议问题