ラジオボタンはRadioGroup
クラスとRadioButton
クラスを利用します。
RadioGroup
クラスには2つ以上のRadioButton
クラスを持たせるようにします。
レイアウトの作成
<RadioGroup
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/RadioGroup">
<RadioButton
android:text="1"
android:id="@+id/RadioButton1"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
<RadioButton
android:text="2"
android:id="@+id/RadioButtoni2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:text="3"
android:id="@+id/RadioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
値の取得方法1
ラジオボタンが選択された項目が変わったことを知るにはRadioGroup
クラスのsetOnCheckedChangeListener
メソッドでOnCheckedChangeListener
インタフェースを登録します。
何が選択されているかはRadioGroup
クラスのgetCheckedRadioButtonId
メソッドの戻り値でIDを知ることができます。何も選択されていない時は-1が返ってきます。
radioGroup = (RadioGroup) findViewById(R.id.RadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) {
RadioButton radioButton = (RadioButton) findViewById(checkedId);
String text = radioButton.getText().toString();
Log.v("checked", text);
} else {
}
}
});
値の取得方法2
決定ボタンをクリックしたときに値を取得したいなどの場合です。
その場合は、RadioGroup
クラスのgetCheckedRadioButtonId
メソッドを利用します。戻り値でそのRadioGroup
のなかで選択されているRadioButton
を取得することができます。onCheckedChanged
メソッドと同様に何も選択されていない場合には-1が返ってきます。
int checkedId = radioGroup.getCheckedRadioButtonId();
if (checkedId != -1) {
RadioButton radioButton = (RadioButton) findViewById(checkedId);
String text = radioButton.getText().toString();
Log.v("checked", text);
} else {
}
参考サイト:
ラジオボタンで複数の選択肢から1つを選択させる / Getting Started « Tech Booster
RadioButtonで複数の選択肢から1つだけ選択する « Tech Booster
Android 奔走記: RadioButton を使ってみた