【问题标题】:Deselect dynamically generated radio buttons after selecting one radio button in android在android中选择一个单选按钮后取消选择动态生成的单选按钮
【发布时间】:2023-03-11 00:54:01
【问题描述】:

我在 android 中从服务器返回的 json 数据动态生成单选按钮。

我可以在单选组中显示单选按钮。还可以获取每个单选按钮的 id。

但是当我点击下一个单选按钮时,所有按钮都保持选中状态。没有一个是未经检查的。

由于无线电号码是动态生成的,因此它的大小会有所不同。

我的代码 sn-ps:

if(type.equals("radio_buttons")){

        String optionName = regData.getOption();
        optionName = Character.toString(optionName.charAt(0)).toUpperCase()+optionName.substring(1);

        List listItem = new ArrayList();
        listItem.add(optionName);

        final RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
        rg.setOrientation(RadioGroup.HORIZONTAL);

        final int radioSize = listItem.size();
        final RadioButton[] rb = new RadioButton[radioSize];

        for(int i=0; i<radioSize; i++){
            rb[i]  = new RadioButton(getActivity());
            rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
            rb[i].setId(i);
            rb[i].setText(optionName);
        }

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                for(int j = 0; j<radioSize; j++){
                    rg.removeViewAt(checkedId);
                }
                /*
                switch (checkedId)
                {
                    case 1:
                        Toast.makeText(OnsiteRegistrationFragment.this.getActivity(), "VIEW ID " + checkedId, Toast.LENGTH_LONG).show();

                    case 2:
                        Toast.makeText(OnsiteRegistrationFragment.this.getActivity(), "VIEW ID " + checkedId, Toast.LENGTH_LONG).show();
                }*/
            }
        });

        this.linearLayout.addView(rg);
} 

如何在 android 中选择一个单选按钮时清除/取消选中其他单选按钮?

【问题讨论】:

  • 尝试为每个单选按钮添加一个 id
  • @zozelfelfo 添加了。你能告诉我现在该怎么做吗?
  • for(int j = 0; j
  • @user3676184 没有。这就是为什么张贴在这里。您知道需要修复的地方吗?
  • 我想你会在这之后得到 NPE for loop.for(int j = 0; j

标签: android android-layout android-activity radio-button


【解决方案1】:
LinkedList<RadioButton> radiobuttons

在创建按钮时,在 for 循环中的单选按钮中添加单选按钮。

for (int i = 0; i < radioSize.size(); i++) {
    RadioButton rb;
    rb = radiobuttons.get(i);
    rg.removeView(rb);
}

【讨论】:

  • 您需要单独删除每个按钮
猜你喜欢
  • 2015-02-27
  • 2011-11-05
  • 1970-01-01
  • 2012-02-21
  • 2011-07-17
  • 2018-07-15
  • 2011-03-16
  • 1970-01-01
  • 2013-10-01
相关资源
最近更新 更多