Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference resources from other module in Android Studio

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?

like image 807
AnnonAshera Avatar asked May 13 '15 19:05

AnnonAshera


1 Answers

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.

-- EDIT --

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"
    />
like image 59
r0adkll Avatar answered Sep 22 '22 12:09

r0adkll