ネイティブのAndroidウィジェットのCompoundButton

AndroidのCompoundButtonは、Buttonを継承した複合ボタンコントロールで、ボタン上に選択枠とラベル文字を表示できます。CompoundButtonには、CheckBoxとRadioButtonの2つの重要なサブクラスがあります。

チェックボックスとは、選択または非選択できるチェックボックス コントロールです。複数のオプションのうち 1 つまたは複数のオプションを選択される状態を表すために使用できます。ユーザーがチェックボックスをクリックすると、選択状態が変更されます。

ラジオボタンとは、1つの選択肢を単独で選択するためのボタン型の控件です。複数ある選択肢の中からどれか1つを選択するような状態で利用されます。ユーザーがラジオボタンをクリックすると、そのラジオボタンの選択状態がオンになり、他のラジオボタンはオフになります。

CompoundButtonには、setChecked()でチェック状態の設定、isChecked()で現在のチェック状態取得など、その状態を制御および取得するためのメソッドが用意されています。

CompoundButtonをレイアウトファイルで使用する際、android:checked属性で初期のチェック状態を指定できます。また、android:text属性でlabelTextを設定できます。

以下に 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>
bannerAds