AndroidでRadioButtonを作る
ラジオボタンで指定した文言をログに出力させる
レイアウトの作成
<RadioGroup android:id="@+id/radio_group" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/radio_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="高坂穂乃果"/> <RadioButton android:id="@+id/radio_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="絢瀬絵里"/> <RadioButton android:id="@+id/radio_3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="南ことり"/> <RadioButton android:id="@+id/radio_4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="園田海未"/> <RadioButton android:id="@+id/radio_5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="星空凛"/> <RadioButton android:id="@+id/radio_6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="西木野真姫"/> <RadioButton android:id="@+id/radio_7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="東條希"/> <RadioButton android:id="@+id/radio_8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="小泉花陽"/> <RadioButton android:id="@+id/radio_9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="矢澤にこ"/> </RadioGroup>
選択したボタンの取得
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group); RadioButton radioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId()); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton checkedButton = (RadioButton) findViewById(checkedId); Log.d("MainActivity", checkedButton.getText().toString()); } }); }
ログ
03-20 09:51:33.603 8544-8544/com.example.hoge.radiobutton D/MainActivity: 高坂穂乃果 03-20 09:51:34.829 8544-8544/com.example.hoge.radiobutton D/MainActivity: 絢瀬絵里 03-20 09:51:35.800 8544-8544/com.example.hoge.radiobutton D/MainActivity: 南ことり 03-20 09:51:37.914 8544-8544/com.example.hoge.radiobutton D/MainActivity: 園田海未