Search code examples
androidbuttontextcolor

Android - Selector does not work for text in button


Using Android Studio. I'm trying to use a selector to make the text in a button turn from white to dark gray. Only the text, not the background of the button.

Here is my Selector xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/darker_gray" android:state_pressed="true"></item>
    <item android:drawable="@android:color/white" android:state_focused="true"></item>
    <item android:drawable="@android:color/white" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>
    <item android:drawable="@android:color/white" android:state_enabled="false"></item>
</selector>

And here is my Button xml:

<Button
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:text="Maps"
    android:id="@+id/buttonMaps"
    android:layout_above="@+id/buttonEmail"
    android:layout_marginBottom="5dp"
    android:layout_centerHorizontal="true"
    android:textColor="@drawable/selector"     <------- **SELECTOR NOT WORKING**
    android:background="#7f2f74a0"             <------- **but it does work if I stick it here**
    android:textSize="20sp" />

In the preview panel, I receive a rendering error message that reads, "Failed to configure parser for /Users...src/main/res/drawable/selector.xml"

I've tried a number of solutions from SO, and nothing has worked, including cleaning and rebuilding the project. Interestingly, I got curious and applied the selector to the button's background and it works - the button background defaults to white and changes to gray when pressed.

Anyone smarter than I am have a solution to this?

Thanks!


Solution

  • Put the text selector in color folder under resources instead of drawable.

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@android:color/darker_gray" android:state_pressed="true"></item>
        <item android:color="@android:color/white" android:state_focused="true"></item>
        <item android:color="@android:color/white" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>
        <item android:color="@android:color/white" android:state_enabled="false"></item>
    </selector>
    

    And the use it like,

    <Button
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="Maps"
        android:id="@+id/buttonMaps"
        android:layout_above="@+id/buttonEmail"
        android:layout_marginBottom="5dp"
        android:layout_centerHorizontal="true"
        android:textColor="@color/selector"  
        android:textSize="20sp" />