【代码】:
toggleMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
UIUtils.toast("开启了密码保护",false);
}else{
UIUtils.toast("关闭了密码保护",false);
}
}
});
【布局】:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/toggle_btn_checked"
></item>
<item
android:state_checked="false"
android:drawable="@drawable/toggle_btn_unchecked"
></item>
</selector>
【需要用到的资源】:
【1】toggle_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/toggle_btn_checked"
></item>
<item
android:state_checked="false"
android:drawable="@drawable/toggle_btn_unchecked"
></item>
</selector>
【2】图片
toggle_btn_checked.png
toggle_btn_unchecked.png
【最后的效果】: