RadioGroup获取radiobutton值的两种办法

layout布局

复制代码
 1  <RadioGroup
 2             android:id="@+id/radiogroup"
 3             android:layout_width="wrap_content"
 4             android:layout_height="wrap_content"
 5             android:orientation="horizontal">
 6 
 7             <RadioButton
 8                 android:id="@+id/man"
 9                 android:layout_width="wrap_content"
10                 android:layout_height="wrap_content"
11                 android:text="男" />
12 
13             <RadioButton
14                 android:id="@+id/woman"
15                 android:layout_width="wrap_content"
16                 android:layout_height="wrap_content"
17                 android:text="女" />
18         </RadioGroup>
复制代码

 

方法一:在radiogroup上设置监听器(不知道为啥一直不能成功)

复制代码
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                        //通过RadioGroup找到radioButton
                        int radioButtonId = radiogroup.getCheckedRadioButtonId();
                        RadioButton radioButton = (RadioButton) findViewById(radioButtonId);
                        //获取值
                        String s = radioButton.getText().toString();
                        user.setSex(s);
                    }
                });
复制代码

 

方法二:利用radiogroup的getchlidcount方法遍历选项

int childCount = radiogroup.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    RadioButton childAt = (RadioButton) radiogroup.getChildAt(i);
                    if (childAt.isChecked()) {
                        user.setSex(childAt.getText().toString());
                    }
                }

 

posted @   打烊宠烊  阅读(773)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示