T.Vert T.Vert - 4 months ago 12
Android Question

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?

Answer

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