Android Switch 按鈕和滑動軌跡圖片設定
阿新 • • 發佈:2019-02-05
<Switch
android:id="@+id/switch_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="18dp"
android:checked="true"
android:track="@drawable/switch_track"//設定滑動軌跡圖片
android:theme="@style/mySwitch"//設定開關主題
/>
設定滑動軌跡圖片,軌跡和按鈕一樣高
<?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/switch_track_on"></item>
<item
android:drawable="@drawable/switch_track_off"></item>
</selector>
可以設定開關顏色和關閉時 的軌跡顏色,不能修改開啟時的軌跡顏色
<!--自定義switch的按鈕和軌跡顏色theme-->
<style name="mySwitch" parent="Theme.AppCompat.Light">
<!-- switch 開啟時的按鈕的顏色 開啟時的軌跡的顏色 30%這個顏色-->
<item name="colorControlActivated">@color/mainTitleBg</item>
<!-- switch關閉時的按鈕的顏色 -->
<item name="colorSwitchThumbNormal">@color/bgWhite</item>
<!-- switch關閉時的軌跡的顏色 -->
<item name="colorForeground">@color/bgWhite</item>
</style>
如果想要軌跡比按鈕低的話,可以自定義xml,設定透明的邊框
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="@android:color/white">
</solid>
<corners
android:radius="32dp">
</corners>
<!-- results in the track looking smaller than the thumb -->
<stroke
android:width="6dp"
android:color="#00ffffff"/>
</shape>