ラジオボタンの状態の取得、設定
1.XMLは以下の通りです。
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroupSelectGrpah"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_button_weight"
android:id="@+id/radioButtonWeight"
android:layout_toLeftOf="@+id/radioGroupSelectGrpah"
android:layout_toStartOf="@+id/radioGroupSelectGrpah" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_button_body_fat_percentage"
android:id="@+id/radioButtonBodyFatPercentage"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/radioGroupSelectGrpah"
android:layout_toEndOf="@+id/radioGroupSelectGrpah" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_button_BMI"
android:id="@+id/radioButtonBMI"
android:layout_toRightOf="@+id/radioGroupSelectGrpah"
android:layout_toEndOf="@+id/radioGroupSelectGrpah" />
</RadioGroup>
2.状態が変化したときにそれを検出して、状態を取ってくるサンプルプログラムは以下の通りです。
2-1.ラジオグループのチェック状態変更イベントを登録
// ラジオグループのオブジェクトを取得
RadioGroup rg = (RadioGroup)view.findViewById(R.id.radioGroupSelectGrpah);
// ラジオグループのチェック状態変更イベントを登録
rg.setOnCheckedChangeListener(new selectGraphOnCheckedChangeListener());
rg.check(R.id.radioButtonWeight);
また、 rg.check(R.id.radioButtonWeight);でラジオボタンを選択しています。
2-2.onCheckedChangeListener本体です。
private class selectGraphOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
// チェック状態変更時に呼び出されるメソッド
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
MakeAndDisplayGraph makeAndDisplayGraph = new MakeAndDisplayGraph();
makeAndDisplayGraph.makeAndDisplayGraph(CalendarAction.STAY, checkedId);
}
}
3.なにかボタンが押されたときに、ラジオボタンの状態を取得するサンプルソースコードです。
private class todayOnClickListener implements View.OnClickListener {
public void onClick(View v) {
RadioGroup radioGroup = (RadioGroup) getActivity().findViewById(R.id.radioGroupSelectGrpah);
int checkedId = radioGroup.getCheckedRadioButtonId();
MakeAndDisplayGraph makeAndDisplayGraph = new MakeAndDisplayGraph();
makeAndDisplayGraph.makeAndDisplayGraph(CalendarAction.TODAY, checkedId);
}
}
int checkedId = radioGroup.getCheckedRadioButtonId();でラジオボタンのIDを取得しています。