android - 如何获取动态添加的单选按钮的选定索引

标签 android

我已经像下面这样动态地添加了单选按钮。

for (int i = 0; i< typeArrayList.size(); i++) {
                   radioButtons[i] = new RadioButton(MainActivity.this);
                   radioButtons[i].setId(i);
                   radioButtons[i].setText(typeArrayList.get(i).toString());
                   if(i==0) {
                       radioButtons[i].setChecked(true);
                   }
                   typeLayout.addView( radioButtons[i]);
                }

当单击时我有一个按钮调用一个方法,动态添加的单选按钮的选定项目(文本)应该传递到该方法。如何获取动态添加的单选按钮的选定单选按钮文本?

最佳答案

在向单选组添加按钮时设置单选按钮 ID 非常重要。

RadioButton rb = new RadioButton(context);
rb.setText(option);
rb.setId(rb.hashCode());
radioGroup.addView(rb);
radioGroup.setOnCheckedChangeListener(mCheckedListner);

现在在您的点击监听器中检查唯一 ID。

private RadioGroup.OnCheckedChangeListener mCheckedListner = new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        JSONArray actionArray = new JSONArray();
        if(group.findViewById(checkedId)!=null) {
            RadioButton rb = ((RadioButton) group.findViewById(checkedId)).getText();
//Your Code here
                }
            }
        }
    };

关于android - 如何获取动态添加的单选按钮的选定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629378/

相关文章:

android - 无法使用默认的 ListView 选择器

android - 知旧时

java - 使用 Android 创建强密码生成器

android - RecyclerView onListItem点击创建新 Intent

java - 更新循环更新对象而不是删除它

android - 适用于 Android 客户管理器的 Cordova 插件(版本 > 3)

android - 我在 android 中从 dropbox 获取照片时检索到此类错误?

java - 如何将参数传递给可运行的方法

android - 为什么android monkey有注入(inject)输入事件的权限?

java - 如何作为方法的结果返回 DataSnapshot 值?