Search code examples
androidtogglebuttonandroid-togglebutton

ToggleButton with custom image and custom text color


I have this toggle:

<ToggleButton
    android:id="@+id/toggle_1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/custom_toggle_bg"
    android:gravity="bottom|center_horizontal" />

and this is drawable resources:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/active" android:state_checked="true"/>
    <item android:drawable="@drawable/default" android:state_checked="false"/>

</selector>

Now i would like that text of ToggleButton (on and off) change color when Toggle change state (only text, not background of entire ToggleButton). How can i do?


Solution

  • You can add the attribute android:textColor="@drawable/color_selector" into your <ToggleButton>

    //color_selector.xml
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" color="@color/text_on" />
        <item android:state_checked="false" color="@color/text_off" />
    </selector>