【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