溫馨提示×

Android widget之CompoundButton

小云
96
2023-09-28 08:02:40
欄目: 編程語言

Android的CompoundButton是一個復(fù)合按鈕控件,它繼承自Button,可以在按鈕上顯示一個選擇框和一個標簽文字。CompoundButton有兩個重要的子類:CheckBox和RadioButton。

CheckBox是一個可以被選中或取消選中的復(fù)選框控件。它可以用來表示多個選項中的一個或多個被選中的狀態(tài)。當用戶點擊CheckBox時,它的選中狀態(tài)會發(fā)生改變。

RadioButton是一個可以被選中的單選按鈕控件。它可以用來表示多個選項中只能選擇一個的狀態(tài)。當用戶點擊RadioButton時,它的選中狀態(tài)會被改變,并且其他的RadioButton會被取消選中。

CompoundButton提供了一些方法來控制和獲取它的狀態(tài),例如setChecked()用于設(shè)置選中狀態(tài),isChecked()用于獲取當前的選中狀態(tài)。

在布局文件中使用CompoundButton時,可以通過設(shè)置android:checked屬性來指定初始的選中狀態(tài)。同時,可以通過設(shè)置android:text屬性來設(shè)置標簽文字。

以下是一個使用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