Search code examples
androidtoggleandroid-buttontogglebuttonandroid-togglebutton

change toggle button text color through xml


Hi i'm trying to change the color of toggle button's text through xml.

I have referred links but its only changing the background color of toggle button but not its text.

I tried with this approach :

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

but only the background is changing.

Note : I don't want to do it in code since there are 21 toggle buttons and setting listeners for each of them is not good.


Solution

  • You shouldn't set the parent of a widget style to be a theme. Instead, you'll want to set it to be the default widget style that you want to modify (e.g. @android:style/Widget.Holo.Button.Toggle).

    In your case, however, you don't need to use a style:

    res/color/toggle_text.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" android:color="#ffffff" />
        <item android:color="#000000" />
    </selector>
    

    res/layout/your_layout.xml:

    ...
    <ToggleButton
        android:id="@+id/toggleButton"
        ...
        android:textColor="@color/toggle_text" />