Search code examples
androidandroid-buttonandroid-togglebutton

How to change ToggleButton color using android:color?


I want to change ToggleButton color based on its state. I've found solution but it doesn't work.

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

I can't use android:color only android:drawable is allowed here. (getting this exception)

Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #3: <item> tag requires a 'drawable' attribute or child tag defining a drawable

Solution

  • Create a xml named colors.xml in res/values folder:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="red">#ff0000</color>
        <color name="green">#00ff00</color>
    </resources>
    

    In drawable folder, create a xml file my_btn_toggle.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="false" android:drawable="@color/red"  />
        <item android:state_checked="true" android:drawable="@color/green"  />
    </selector>
    

    and in xml section define your toggle button:

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New ToggleButton"
        android:id="@+id/toggleButton"
        android:background="@drawable/my_btn_toggle"/> 
    

    To know more here is the link