Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Button Text Color Always Pink

I am trying to change both the button text color and the button background color when the button toggles between selected state and not. The background works perfectly, but the text just shows as pink (the default colorPrimary, which I have changed).

res/drawable/map_button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>

    <item android:state_selected="true">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <solid android:color="@color/colorPrimary"/>
        </shape>
    </item>
</selector>

res/drawable/map_button_text.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <color android:color="@color/colorPrimary"/>
    </item>

    <item android:state_selected="true">
        <color android:color="@android:color/white"/>
    </item>
</selector>

res/styles/styles.xml

<style name="Button.Map">
    <item name="android:layout_height">0dp</item>
    <item name="android:layout_weight">1</item>
    <item name="android:layout_margin">4dp</item>
    <item name="android:background">@drawable/map_button_background</item>
    <item name="android:textColor">@drawable/map_button_text</item>
</style>

Also, the text color never changes, it just stays pink all the time. I tried adding <item android:color="@color:/colorPrimary"/> to be used as a default, but it still doesn't work.

Any ideas on what's causing it?

like image 652
Cody Harness Avatar asked Dec 24 '22 22:12

Cody Harness


1 Answers

You have a a few problems.

First, your <item> elements should have the android:color attribute on them directly, not in a child <color> element.

Second, android:textColor needs to refer to a color resource (or a literal color value).

You have placed your map_button_text resource in your res/drawable folder, which tells Android to interpret it as a Drawable, not a color.

If you move that file to res/color and refer to it via @color/map_button_text you should get what you want.

Finally, you should also define a default state for your selector (one without any android:state_ attributes).

Your final XML should look something like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorPrimary" android:state_selected="false"/>

    <!-- Default state -->
    <item android:color="@android:color/white"/>
</selector>
like image 125
Bryan Herbst Avatar answered Dec 31 '22 18:12

Bryan Herbst