1.首先在布局中加入以下片段:
<ToggleButton
android:id="@+id/msgTimeTogBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginRight="15dp"
android:background="@android:color/transparent"
android:button="@drawable/more_msg_set_switchbtn"
android:layout_marginLeft="5dp"
android:text=""
android:textOff=""
android:textOn=""/>
<!-- 末尾三行实现开关上是否显示字,即off,on等字样-->
2.在drable下创建more_msg_set_switchbtn.xml,内容如下
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/open" /><!--设置默认是开的状态-->
<item android:state_checked="true" android:drawable="@drawable/off" />
</selector>
3.在drable-hdpi加入图片open,off
4.在Activity中find出来,设置OnCheckedChangeListenner做开关处理
msgTimeTogbtn= (ToggleButton) findViewById(R.id.msgTimeTogBtn);
msgTimeTogbtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
}else{
}
}
});