什么是Switch
Switch是一种用于显示开关状态的UI控件.
基础样例
1.普通开关
效果图
代码
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Switch" />
2.设置字号
效果图
代码
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是20号字体的Switch"
android:textSize="20sp" />
3.设置颜色
效果图
代码
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是红色的Switch"
android:textColor="#FF0000" />
4.设置加粗
效果图
代码
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是加粗的Switch"
android:textStyle="bold" />
5.设置选中
效果图
代码
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="我是被选中的Switch" />
5.设置开关按钮文字
效果图
代码
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:text="开关上显示文字"
android:textOff="已关闭"
android:textOn="已打开" />
基础样例完整源代码
常用属性说明
属性名
用途
android:layout_width
设置控件宽度,可设置为:match_parent(和父控件一样),wrap_content(按照内容自动伸缩),设置固定值(如200dp)
android:layout_height
设置控件高度,可设置为:match_parent(和父控件一样),wrap_content(按照内容自动伸缩),设置固定值(如200dp)
android:gravity
控件内对齐方式
android:background
设置背景,可以是色值(如#FF0000)或图片等
android:visibility
可选值: visible(显示), invisible(隐藏,但是仍占据UI空间),gone(隐藏,且不占UI空间)
android:text
设置文本内容
android:textSize
设置字号
android:textColor
设置颜色
android:textStyle
设置字体样式,可选值:normal(正常),bold(加粗),italic(斜体)
android:checked
是否选中,可选值:true(选中),false(未选中)
android:textOff
设置开关未选中时显示的文字
android:textOn
设置开关选中时显示的文字
android:showText
设置是否显示开关上文字
android:switchMinWidth
设置开关的最小宽度
android:track
设置底部图片
android:thumb
设置滑块图片
更多属性及实际效果,可以在开发工具里自行体验.