T.Vert
T.Vert

Reputation: 279

How to reference a color from layout

This is my styles.xml file

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#6d3655</item>
    <item name="colorPrimaryDark">#442142</item>
    <item name="colorAccent">#de8573</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

And I want to access colorPrimary from my layout. For example I try to apply the color to some TextField. I set "textColor" property to "@style/AppTheme.colorPrimary" but it doesn't work. Why?

Upvotes: 1

Views: 2069

Answers (2)

Marcin Koziński
Marcin Koziński

Reputation: 11074

You don't have to save the color as a resource in colors.xml. You can reference a color (or any other value) directly from theme like this:

android:textColor="?attr/colorPrimary"

?attr/ is the syntax for accessing theme attribute values.

Upvotes: 9

Zahidul Islam
Zahidul Islam

Reputation: 3190

You have to save the Color in the colors.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6d3655</color>
    <color name="colorPrimaryDark">#442142</color>
    <color name="colorAccent">#de8573</color>
</resources>

Also, in your styles.xml file change like this way ,

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

So, now you can access the color from the layout's element,

<Button
    android:background="@color/colorPrimary"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Upvotes: 0

Related Questions