Android入门逆引手册 - 07 单选框(RadioButton)的使用
这里介绍RadioButton类和RadioGroup类的使用方法。
android.widget.RadioButton
android.widget.RadioGroup
●使用单选框的时候,要用RadioGroup来分组
●选择RadioGroup里的单选框的时候,将调用RadioGroup的Check·()方法
●追加单选框被选择时处理的时候,
1.调用setOnCheckedChangeListener()方法,并把RadioGroup.OnCheckedChangeListener实例作为参数传入
2.在RadioGroup.OnCheckedChangeListener的onCheckedChanged()方法里,取得被选中单选框的实例
例程源码(Java)
01.
RadioGroup radioGroup = (RadioGroup) findViewById(id.radioGroup);
02.
03.
radioGroup.check(id.radioButtonGreen);
04.
05.
RadioButton radioButton = (RadioButton) findViewById(
06.
radioGroup.getCheckedRadioButtonId());
07.
08.
Log.v(
"Test"
, String.valueOf(radioButton.getText()));
09.
10.
radioGroup.setOnCheckedChangeListener(
11.
new
RadioGroup.OnCheckedChangeListener() {
12.
public
void
onCheckedChanged(
13.
RadioGroup group,
14.
int
checkedId) {
15.
RadioButton radioButton = (RadioButton) findViewById(checkedId);
16.
17.
Log.v(
"Test"
, String.valueOf(radioButton.getText()));
18.
}
19.
});
例程源码(Resource)
01.
<
RadioGroup
android:id
=
"@+id/radioGroup"
02.
android:layout_width
=
"wrap_content"
03.
android:layout_height
=
"wrap_content"
>
04.
<
RadioButton
android:id
=
"@+id/radioButtonRed"
05.
android:layout_width
=
"wrap_content"
06.
android:layout_height
=
"wrap_content"
07.
android:text
=
"@string/Red"
/>
08.
<
RadioButton
android:id
=
"@+id/radioButtonGreen"
09.
android:layout_width
=
"wrap_content"
10.
android:layout_height
=
"wrap_content"
11.
android:text
=
"@string/Green"
/>
12.
<
RadioButton
android:id
=
"@+id/radioButtonBlue"
13.
android:layout_width
=
"wrap_content"
14.
android:layout_height
=
"wrap_content"
15.
android:text
=
"@string/Blue"
/>
16.
</
RadioGroup
>
参考资源
● RadioButton | Android Developers
● RadioGroup | Android Developers