android-How to make custom toggle button

user3718930 picture user3718930 · Jun 22, 2014 · Viewed 7.1k times · Source

I want to make a custom toggle button , for instance when I click on the button , the star turns on and when I click again ,the star turns off. i've tried some codes but they change the button to an image and when I click on it ,the image changes . I mean ,there is no button , it's just an image .

I want the image to be inside the button , like the default toggle button and I just need to change the image inside it .

How can I do so ?

thanks

Answer

Basbous picture Basbous · Jun 22, 2014

create toggle_selector.xml in res/drawable

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

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

reference https://stackoverflow.com/a/20300753/712960