先不廢話暇咆,上圖
可以自定義滑塊 和背景哦~
2、開始進(jìn)入代碼環(huán)節(jié)
Java部分概行,監(jiān)聽和調(diào)用
mToolSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
showShortToast("選中");
}else {
showShortToast("沒選中");
}
}
});
3傻谁、switch控件屬性介紹
android:showText:設(shè)置on/off的時候是否顯示文字,boolean
android:splitTrack:是否設(shè)置一個間隙葬项,讓滑塊與底部圖片分隔,boolean
android:switchMinWidth:設(shè)置開關(guān)的最小寬度
android:switchPadding:設(shè)置滑塊內(nèi)文字的間隔
android:switchTextAppearance:設(shè)置開關(guān)的文字外觀鸟召,暫時沒發(fā)現(xiàn)有什么用...
android:textOff:按鈕沒有被選中時顯示的文字
android:textOn:按鈕被選中時顯示的文字
android:textStyle:文字風(fēng)格毙芜,粗體撤逢,斜體寫劃線那些
android:track:底部的圖片
android:thumb:滑塊的圖片
android:typeface:設(shè)置字體
4娄柳、進(jìn)入正題 xml部分代碼編寫如下
<Switch
android:id="@+id/tool_switch"
android:textColor="@color/fsk_subtitle_black"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:track="@drawable/switch_selector_green"
android:thumb="@drawable/switch_white_circle_selector"
android:text="開關(guān)"
/>
5寓辱、樣式編寫代碼如下
switch_selector_green
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_bg_selected" android:state_checked="true"/>
<item android:drawable="@drawable/switch_bg_normal" android:state_checked="false"/>
</selector>
switch_bg_selected
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
>
<solid android:color="@color/fsk_green"/>
<size android:width="40dp"
android:height="24dp"/>
<corners android:radius="20dp"/>
</shape>
switch_bg_normal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
>
<solid android:color="@color/fsk_base_bg"/>
<size android:width="40dp"
android:height="24dp"/>
<corners android:radius="20dp"/>
</shape>
switch_white_circle_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_white_circle_selected" android:state_checked="true"/>
<item android:drawable="@drawable/switch_white_circle_normal" android:state_checked="false"/>
</selector>
switch_white_circle_selected
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<stroke android:width="1dp" android:color="@color/fsk_green"/>
<solid android:color="@color/white"/>
<size android:width="24dp"
android:height="24dp"/>
</shape>
switch_white_circle_normal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<stroke android:width="1dp" android:color="@color/fsk_base_bg"/>
<solid android:color="@color/white"/>
<size android:width="24dp"
android:height="24dp"/>
</shape>
樣式搞定 ,當(dāng)然了 要是shape實(shí)現(xiàn)不了赤拒,就用圖片咯秫筏!