1,获取RadioGroup控件:
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.myRadioGroup)
;
2,获取RadioButton控件;
RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId())
;
3,获取选中的radio的值:
String text = radioButton.getText().toString()
;
4,为radioGroup添加监听事件,用来监听组件内部的事件响应:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//在这个函数里面用来改变选择的radioButton的数值,以及与其值相关的 //任何操作,详见下文
selectRadioBtn();
}
})
;
5,在onCreat中需要初始化上面的四条信息;
6,整体的使用样例:
布局文件xml中的内容:
<RadioGroup
android:id="@+id/sex_group"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男"/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"/>
</RadioGroup>
代码实现:
private RadioGroup mSex_group;
private RadioButton mMale;
private RadioButton mFemale;
private String sexName;
mSex_group = (RadioGroup) findViewById(R.id.sex_group);
mMale = (RadioButton) findViewById(R.id.male);
mFemale = (RadioButton) findViewById(R.id.female);
mSex_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (mMale.getId() == checkedId) {
sexName = mMale.getText().toString();
} else if (mFemale.getId() == checkedId) {
sexName = mFemale.getText().toString();
}
}
});
----------
如有错误,欢迎指教!谢谢阅读