简体   繁体   中英

android-How to make custom toggle button

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM