首页 > 解决方案 > 动态添加的 RadioButtons 不监听 onCheckChangedListener()

问题描述

我需要动态添加 RadioGroups 和 RadioButtons 并生成所需的视图并在我动态创建的 RadioGroup 上实现 onCheckChangedListener() 。问题是,当一个新添加的按钮被选中时,当我点击其他按钮时它并没有被取消选中。我已经检查了这个 -动态添加单选按钮时单选组中的问题,但无济于事。

我正在处理一个片段并在其中动态添加视图。单选按钮不显示检查更改行为。请帮我解决这个问题。

//optionsGroup(RadioGroup),optionButton(RadioButton) 

    optionsGroup = new RadioGroup(getActivity());
    optionsGroup.setId(radioGroupCount);
    optionsGroup.setPadding(20, 20, 20, 20);
    optionsGroup.setLayoutParams(layparams);
    radioGroupList.add(optionsGroup);
    ArrayList<Options> RadioButtonOptions = question.getQuestionOptions().getOptions();
    for (int i = 0; i < RadioButtonOptions.size(); i++) {
        optionButton = new RadioButton(getActivity());
        optionButton.setId(i);
        optionButton.setText(RadioButtonOptions.get(i).getOptionValue());
        optionsGroup.addView(optionButton);
        optionsGroup.clearCheck();
    }
    optionsGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
          for(int rb=0;rb<optionsGroup.getChildCount();rb++){
              RadioButton btn = (RadioButton) optionsGroup.getChildAt(rb);
              if(checkedId==btn.getId()){
                  radioGroupAnswerList.clear();
                  radioGroupAnswerList.add(btn.getText().toString());
                  return;
              }

          }
        }
    });
    holderlayout.addView(optionsGroup);

标签: androidandroid-radiogrouponcheckedchanged

解决方案


如果单击了一个单选按钮,您需要取消选中其他单选按钮吗?所有这一切都将动态创建单选按钮和单选组..然后你必须这样做..

//optionsGroup(RadioGroup),optionButton(RadioButton) 

optionsGroup = new RadioGroup(getActivity());
optionsGroup.setId(radioGroupCount);
optionsGroup.setPadding(20, 20, 20, 20);
optionsGroup.setLayoutParams(layparams);
radioGroupList.add(optionsGroup);
ArrayList<Options> RadioButtonOptions = question.getQuestionOptions().getOptions();
for (int i = 0; i < RadioButtonOptions.size(); i++) {
    optionButton = new RadioButton(getActivity());
    optionButton.setId(i);
    optionButton.setText(RadioButtonOptions.get(i).getOptionValue());
    optionsGroup.addView(optionButton);
    optionsGroup.clearCheck();
}
optionsGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
      for(int rb=0;rb<optionsGroup.getChildCount();rb++){
          RadioButton btn = (RadioButton) optionsGroup.getChildAt(rb);
          if(checkedId==btn.getId()){
              radioGroupAnswerList.clear();
              radioGroupAnswerList.add(btn.getText().toString());
              optionsGroup.clearCheck();
               if (isChecked) {
                 optionsGroup.check(btn.getId());
              }
              return;
          }

      }
    }
});
holderlayout.addView(optionsGroup);

推荐阅读