一、ToggleButton(开关按钮)
1.1、简介
ToggleButton 类似开关有开和关两种状态,不同的状态下可以有不同的文本。
public class ToggleButton extends CompoundButton
Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF"。
这是一种特殊的有两种状态的继承至CompoundButton的控件,在不同的状态会有高亮显示效果,既然是继承至CompoundButton,那我们也随便看一下CompoundButton的介绍:
A button with two states, checked and unchecked. When the button is pressed
or clicked, the state changes automatically.
1.2、属性
android:checked = “true”
默认为选中状态,反之false即是默认为非选中状态。
android:textOff = “张起灵” 未选中状态下的文本是张起灵
android:textOn = “张无忌” 选中状态下的文本是张无忌
1.3.1、示例1
效果图:
XML:
<ToggleButton android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ToggleButton" android:textAllCaps="false" android:textOff="张起灵" android:textOn="张无忌" />
1.3.2、示例2
同样的,我们可以监听不同的状态来设置不同的背景,来适配不同的使用场景,这个背景设置和Button中的一模一样。只是针对的状态不同而已,记得在Button中,我们的Drawable如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorAccent"></item>
<item android:state_pressed="false" android:drawable="@color/colorPrimary"></item>
</selector>
在我们的ToggleButton中,我们的背景Drawable如下: