为了账号安全,请及时绑定邮箱和手机立即绑定

【Android学习笔记】如何获取RadioGroup中RadioButton的值?

标签:
Android C

图片描述
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();
                }
            }
        });

----------

如有错误,欢迎指教!谢谢阅读
点击查看更多内容
18人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消