【Android】ラジオボタンの使い方

ラジオボタン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);// (Fragmentの場合は「getActivity().findViewById」にする)

    // ラジオボタンのテキストを取得
    String text = radioButton.getText().toString();

    Log.v("checked", text);
} else {
    // 何も選択されていない場合の処理
}

参考サイト:

ラジオボタンで複数の選択肢から1つを選択させる / Getting Started « Tech Booster

RadioButtonで複数の選択肢から1つだけ選択する « Tech Booster

Android 奔走記: RadioButton を使ってみた