■レイアウトファイル
以下のようにすることで画面にラジオボタンを配置できる。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RadioGroup android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/RadioGroup"> <RadioButton android:text="1" android:id="@+id/btn1" android:layout_height="wrap_content" android:layout_width="wrap_content" /> <RadioButton android:text="2" android:id="@+id/btn2" android:layout_height="wrap_content" android:layout_width="wrap_content" /> <RadioButton android:text="3" android:id="@+id/btn3" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </RadioGroup> </LinearLayout>
■状態の取得
殆どの場合はコードからラジオボタンの状態を検知したいはずだ。
package info.justoneplanet.android.sample.radiobutton; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; public class RadioButtonActivity extends Activity implements OnCheckedChangeListener { private RadioGroup mRadioGroup; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mRadioGroup = (RadioGroup) findViewById(R.id.RadioGroup); mRadioGroup.setOnCheckedChangeListener(this); } // チェックの状態が変更されるごとに発火する @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (-1 == checkedId) { // 何もチェックされていないとき } else { // チェックされているとき Log.e("checked", getResources().getResourceEntryName(checkedId));// viewのID名を表示 } } // 保存ボタンなどで取得したい場合は以下のメソッドを利用する @Override public void onPause() { mRadioGroup.getCheckedRadioButtonId(); } }