android – How to reference a color from layout-ThrowExceptions

Exception or error:

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?

How to solve:

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" />

###

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.

###

Color resides in color.xml file, which can be found at res > values > color.xml

To apply color to any view just use

@color followed by name
Example-

android:background=”@color/colorPrimary”

Leave a Reply

Your email address will not be published. Required fields are marked *