Android のラジオボタンコントロールの使い方
AndroidのRadioButtonコントロールを使用するには、次の手順に従う必要があります。
- XMLレイアウトファイルにRadioButtonを追加する。例えば次のコードではRadioButtonをLinearLayoutに追加します。
<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" />
- JavaクラスでRadioButtonを見つけます。FindViewById()メソッドを使用してIDでRadioButtonを探すことができます。例:
RadioButton radioButton1 = findViewById(R.id.radioButton1);
RadioButton radioButton2 = findViewById(R.id.radioButton2);
- RadioButtonのチェック状態が変化した際のリスナーを、オプションで設定可能。ユーザーがRadioButtonの選択/選択解除を行った際に処理を実行したい場合は、リスナーを設定します。例:
radioButton1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 当用户选中radioButton1时执行的操作
} else {
// 当用户取消选中radioButton1时执行的操作
}
}
});
- 必要時、RadioButtonの選択状態を取得する。RadioButtonの選択状態を確認するにはisChecked()メソッドを使用することができる。例:
if (radioButton1.isChecked()) {
// radioButton1被选中
} else {
// radioButton1未被选中
}
これらの手順により、AndroidのRadioButtonコントロールの使用を開始できます。RadioButtonの動作と外観をカスタマイズするには、必要に応じてさらに多くのプロパティとリスナーを設定できます。