动态创建的无线电组没有听到检查改变听众

时间:2016-06-26 09:59:51

标签: android radio-button android-radiogroup

我创建了一个带有3个单选按钮的动态广播组。我的问题是所有3个按钮都可以点击,而广播组也没有听到检查更改。我想在无线电组内的单选按钮的默认行为,其中只能检查一个单选按钮。

RadioButton[] rb = new RadioButton[question.getAnswers().size()];
RadioGroup rg = new RadioGroup(getActivity());
rg.setOrientation(RadioGroup.VERTICAL);
questionContainer.addView(rg);

for (int i =0; i < question.getAnswers().size(); i++) {
    rb[i] = new RadioButton(getActivity());
    rb[i].setText(question.getAnswers().get(i));
    rg.addView(rb[i]);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
         Log.e(debugTag, "radio button position: "+checkedId);
    }
});

questionContainer是我的片段的LinearLayout容器

1 个答案:

答案 0 :(得分:0)

问题实际上来自我用来创建单选按钮的库。经过一些挖掘和@R提供的2个非常有用的链接。 Kirill我没有创建一个RadioGroup来将单选按钮放在其中。我只是自己处理CompoundButton(此类的RadioButton扩展)检查更改侦听器。

final RadioButton[] rb = new RadioButton[question.getAnswers().size()];

com.rey.material.widget.CompoundButton.OnCheckedChangeListener c = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (isChecked) {
            for (RadioButton aRb : rb) {
                aRb.setChecked(aRb == compoundButton);
            }
        }
    }
};

for (int i =0; i < question.getAnswers().size(); i++) {
    rb[i] = new RadioButton(getActivity());
    rb[i].setId(i);
    rb[i].setOnCheckedChangeListener(c);
    rb[i].setChecked(false);
    rb[i].setText(question.getAnswers().get(i));
    questionContainer.addView(rb[i]);
}