什么是Switch
Switch是一種用于顯示開關(guān)狀態(tài)的UI控件.
基礎(chǔ)樣例
1.普通開關(guān)
效果圖

代碼
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Switch" />
2.設(shè)置字號
效果圖

代碼
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是20號字體的Switch"
android:textSize="20sp" />
3.設(shè)置顏色
效果圖

代碼
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是紅色的Switch"
android:textColor="#FF0000" />
4.設(shè)置加粗
效果圖

代碼
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是加粗的Switch"
android:textStyle="bold" />
5.設(shè)置選中
效果圖

代碼
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="我是被選中的Switch" />
5.設(shè)置開關(guān)按鈕文字
效果圖


代碼
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:text="開關(guān)上顯示文字"
android:textOff="已關(guān)閉"
android:textOn="已打開" />
基礎(chǔ)樣例完整源代碼
https://gitee.com/hspbc/SwitchDemo
常用屬性說明
| 屬性名 | 用途 |
|---|---|
| android:layout_width | 設(shè)置控件寬度,可設(shè)置為:match_parent(和父控件一樣),wrap_content(按照內(nèi)容自動(dòng)伸縮),設(shè)置固定值(如200dp) |
| android:layout_height | 設(shè)置控件高度,可設(shè)置為:match_parent(和父控件一樣),wrap_content(按照內(nèi)容自動(dòng)伸縮),設(shè)置固定值(如200dp) |
| android:gravity | 控件內(nèi)對齊方式 |
| android:background | 設(shè)置背景,可以是色值(如#FF0000)或圖片等 |
| android:visibility | 可選值: visible(顯示), invisible(隱藏,但是仍占據(jù)UI空間),gone(隱藏,且不占UI空間) |
| android:text | 設(shè)置文本內(nèi)容 |
| android:textSize | 設(shè)置字號 |
| android:textColor | 設(shè)置顏色 |
| android:textStyle | 設(shè)置字體樣式,可選值:normal(正常),bold(加粗),italic(斜體) |
| android:checked | 是否選中,可選值:true(選中),false(未選中) |
| android:textOff | 設(shè)置開關(guān)未選中時(shí)顯示的文字 |
| android:textOn | 設(shè)置開關(guān)選中時(shí)顯示的文字 |
| android:showText | 設(shè)置是否顯示開關(guān)上文字 |
| android:switchMinWidth | 設(shè)置開關(guān)的最小寬度 |
| android:track | 設(shè)置底部圖片 |
| android:thumb | 設(shè)置滑塊圖片 |
更多屬性及實(shí)際效果,可以在開發(fā)工具里自行體驗(yàn).