Search code examples
androidtogglebuttonindicator

How to change indicator color in Toggle Button ( Android)


Hi every body I want to use toggle button but with different indicator color (like green or red), How to change the color of indicator .

See default indicator on imgur


Solution

  • I think you are going to have to create 2 custom images of the button and then use a drawable xml as the background.

    For Example:

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/btntoggle_selector"
        android:textColor="@android:color/white"
        android:textOff="Toggle Button OFF"
        android:textOn="Toggle Button ON "
        android:onClick="onToggleButtonClick" />
    

    Then the btntoggle_selector xml

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

    bg_selected and bg_normal are just images like 9-patch.

    See the Android developer guide on 9-patch images