温馨提示×

Android widget之CompoundButton

小云
88
2023-09-28 08:02:40
栏目: 编程语言

Android的CompoundButton是一个复合按钮控件,它继承自Button,可以在按钮上显示一个选择框和一个标签文字。CompoundButton有两个重要的子类:CheckBox和RadioButton。

CheckBox是一个可以被选中或取消选中的复选框控件。它可以用来表示多个选项中的一个或多个被选中的状态。当用户点击CheckBox时,它的选中状态会发生改变。

RadioButton是一个可以被选中的单选按钮控件。它可以用来表示多个选项中只能选择一个的状态。当用户点击RadioButton时,它的选中状态会被改变,并且其他的RadioButton会被取消选中。

CompoundButton提供了一些方法来控制和获取它的状态,例如setChecked()用于设置选中状态,isChecked()用于获取当前的选中状态。

在布局文件中使用CompoundButton时,可以通过设置android:checked属性来指定初始的选中状态。同时,可以通过设置android:text属性来设置标签文字。

以下是一个使用CheckBox的例子:

<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox"
android:checked="true" />

以下是一个使用RadioButton的例子:

<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radiobutton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 1" />
<RadioButton
android:id="@+id/radiobutton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 2" />
</RadioGroup>

0