RadioButtonとRadioGroupクラスを使います。RadioButtonはButtonクラスを継承しており、ボタンの一種となります。Buttonクラスの機能もそのまま使うことができます。このRadioButtonクラスはラジオボタンだけでなくテキストも添えて表示することも可能です。
通常のボタンと大きく異なるのは、複数のラジオボタンをまとめたグループを作る必要がある、ということです。グループされたボタンの中で1つだけが押された状態になります。それをRadioGroupクラスで管理します。
例)3つのラジオボタンをグループ化して、初期値の設定や、現在押されているボタンの読み出し、ラジオボタンを押したとき、そのボタンのテキストを読み出します。
<RadioGroup
android:id="@+id/menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/check1" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/check2" />
<RadioButton
android:id="@+id/radio3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/check3" />
</RadioGroup>
public class SampleAppActivity extends Activity {
private final static String TAB = "SampleAppActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioGroup menu = (RadioGroup) findViewById(R.id.menu);
menu.check(R.id.radio2);
Log.i(TAB, "ID:" + menu.getCheckedRadioButtonId());
menu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radio = (RadioButton) findViewById(checkedId);
Log.i(TAB,"Checked:" + radio.getText());
}
});
}
}
参考:Android Developers:RadioButton
参考:Android Developers:RadioGroup

No comments:
Post a Comment