How to reference a string in strings.xml of an Android library in code?
A library project should be able to reference it's resources in exactly the same way.
Is there a specific use case / code sample that illustrates this not working?
Any strings defined in the parent project will overwrite the library. Even actionbarsherlock uses a prefix ex. abs__action_bar_home_description
//For boolean values
int resId = context.getResources().getIdentifier("bool_ID", "bool", context.getPackageName());
if(resId != 0){
System.out.println(context.getResources().getBoolean(resId));
}
//For String values
int resStringId = context.getResources().getIdentifier("string_ID", "string", context.getPackageName());
if(resStringId != 0){
System.out.println(context.getResources().getString(resStringId));
}
As you indicated to reference a string resource defined in your library you can use getString() method, you only need a Context, but in your example the conflict is generated by the same name of the strings.
When you define a resource in your library you have a conflict if you use the same name of a resource in the application module. To avoid conflicts you have to use unique names, for example using a common prefix for resource names in the library, it is not sufficient the different package name.
To resolve you can use the following names:
- mylib_foo in your library
- foo in your application
Source from android documentation: http://developer.android.com/tools/projects/index.html#considerations
As you develop your library modules and dependent applications, keep the points listed below in mind:
Resource conflicts
Since the tools merge the resources of a library module with those of a dependent application module, a given resource ID might be defined in both modules. In this case, the tools select the resource from the application, or the library with highest priority, and discard the other resource. As you develop your applications, be aware that common resource IDs are likely to be defined in more than one project and will be merged, with the resource from the application or highest-priority library taking precedence.
Use prefixes to avoid resource conflicts
To avoid resource conflicts for common resource IDs, consider using a prefix or other consistent naming scheme that is unique to the module (or is unique across all project modules).