Android – Create Drawable For Single Color

android

I have a button that when clicked, I would like the color of the text to change from white to yellow. I created a selector XML file in my drawable folder. My question is, I don't know how to set the color of my text when state_pressed is true. I tried using hexadecimals but kept getting the following error:

<item> tag requires a 'drawable' attribute or child tag defining a drawable

I assume the color has to come from my drawable folder? I finally found this solution but am limited to the amount of colors I can use

<item
    android:state_pressed="true"
    android:drawable="@android:color/holo_blue_light">
</item>

How can I solve this? Can I create separate XML file in my drawable folder with just one color that I can reference? If so, how do I do this? Or is there a simpler solution? Thank you.

Best Answer

First create a colors.xml resource file in your app/resource/values for example like this one below:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="gray">#D2D2D2</color>
    <color name="dark_gray">#ff838383</color>
    <color name="transparent_black">#1A000000</color>
</resources>

Then you can use the colors defined in colors.xml to create your selector.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:color="@color/gray" />
    <item android:state_focused="true" android:state_pressed="true" android:color="@color/dark_gray" />
    <item android:state_focused="false" android:state_pressed="true" android:color="@color/dark_gray" />
    <item android:color="@color/transparent_black" />
</selector>

Place the xml in a file at res/drawable folder i.e. res/drawable/button_text_color.xml. Then just set the drawable as text color in your button:

android:textColor="@drawable/button_text_color"