布局:
<ToggleButton android:id="@+id/tb_record" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="5dp" android:background="@android:color/transparent" android:button="@drawable/setting_toggle" android:checked="false" android:text="" android:textOff="" android:textOn="" />
示例图:
drawable下setting_toggle的代码:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_checked="true" android:state_pressed="true" android:drawable="@mipmap/setting_toggle_on" /> <item android:state_checked="false" android:state_pressed="true" android:drawable="@mipmap/setting_toggle_off" /> <item android:state_checked="false" android:drawable="@mipmap/setting_toggle_off" /> <item android:state_checked="true" android:drawable="@mipmap/setting_toggle_on" /> </selector>
setting_toggle_on与setting_toggle_off的两张图片:
// 添加监听事件 tb_record.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ //选中 }else{ //未选中 } } });