Android RadioGroup OnCheckedChangeListener

时间:2014-12-08 13:26:10

标签: android checkbox listener android-radiogroup

我有一个同时实现Checkbox.OnCheckedChangeListenerRadioGroup.OnCheckedChangeListener的活动这些组都是动态生成的,并且与Activity传递的是listener

然而,当我点击一个RadioGroup时,RadioGroup.OnCheckChangeListener被完全忽略了,但这里变得奇怪了。它会触发CheckBox.OnCheckChangeListener!我尝试在传递之前将活动转换为RadioGroup侦听器,但RadioGroup甚至无法接受它,只有CheckBox侦听器才能通过。

@Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(subquestion.getQuestionType().equals("MULTIPLE_CHOICE_MULTI_ANSWER")) {
                String selected = buttonView.getText().toString();
                if (subquestion.getAnswer().getDataList() != null) {
                    Answer answer = subquestion.getAnswer();
                    ArrayList<String> checked = answer.getDataList();
                    if (checked.contains(selected)) {
                        checked.remove(selected);
                        Log.d("Checkbox" + buttonView.getId(), "unchecked");
                    } else {
                        checked.add(selected);
                        Log.d("Checkbox" + buttonView.getId(), "checked");
                    }
                } else {
                    ArrayList<String> checked = new ArrayList<String>();
                    checked.add(selected);
                    subquestion.getAnswer().setDataList(checked);
                    Log.d("Checkbox" + buttonView.getId(), "checked");
                }
            }
            if(subquestion.getQuestionType().equals("MULTIPLE_CHOICE_SINGLE_ANSWER")) {
                RadioGroup group = buttonView; //CAN'T BE DONE
                String selected = group.getFocusedChild().getId() + "";
                subquestion.getAnswer().setData(selected);
                Log.d("Radiobutton " + selected + group.getFocusedChild().getId(), "selected");
            }
        }

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
           //This does NOTHING, can't even be passed to the RadioGroup as a listener
        }

如何从buttonView获取RadioGroup?我在代码中生成所有内容,每次都不同,所以没有静态ID来确定点击的内容。我把一个id传递给了radiobuttons,让我知道哪个是哪个,但我不能这样做。

它非常适用于复选框,只是Android似乎抛出了错误的事件并为RadioGroup使用了错误的事件处理程序。

感谢您阅读!

1 个答案:

答案 0 :(得分:2)

为RadioGroup.OnCheckChangeListener调用此方法并将RadioGroup作为参数传递

public void onRadioChangeListener(RadioGroup radioGroup){

    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // write your code here
        }
    });
}