I have a main app module as well as a few library modules.
How can my Library module reference resources from the Main App module.
For instance: My base app has a colors.xml which has a color item called "AppPrimary" which is blue.
In my library I want a view in an xml layout to reference @color/AppPrimary color, but that doesn't work.
How can I achieve this?
Edit: I should specify this isn't specifically appCompat resources. Just generic strings/colors/styles/in my main module. How can I reference them in the same project in my library module colors.xml/strings.xml?
In your library module in the xml layout reference ?attr/colorPrimary
instead of @color/AppPrimary
This references the color palette attributes from your app's theme. i.e.;
<item name="colorPrimary">@color/AppPrimary</item>
You can also refer to the other color palette attributes like:
<item name="colorPrimaryDark">...</item> -> ?attr/colorPrimaryDark
<item name="colorAccent">...</item> -> ?attr/colorAccent
and so on.
Please refer to this documentation
CAVEAT:
These examples refer the AppCompat implementation in the theme. i.e. no android:
namespace prefix.
The short answer is that you simply can't 'get' a defined color from your main module referenced to your libraries colors.xml file.
You can however leverage custom defined attributes in your theme to achieve the same effect.
This works by declaring a generic styleable in your attrs.xml
file in the library module, Something like this:
<declare-styleable name="BaseTheme">
<attr name="someColor" format="reference|color" />
</declare-styleable>
Note: The name of the styleable has no bearing on this implementation so feel free to name it whatever you want.
Then in your main module's theme definition in your 'style.xml' or 'theme.xml' file you'll want to set this attribute to the color you want to share, like this:
<style name="Theme.Example" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Color Palette -->
<item name="colorPrimary">...</item>
<item name="colorPrimaryDark">...</item>
<item name="colorAccent">...</item>
<!-- Here we define our custom attributes -->
<item name="someColor">@color/dark_blue</item>
</style>
Once this is defined, you can reference the attribute in your library module XML code. e.g.;
<TextView
...
android:textColor="?attr/someColor"
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With