从单选按钮和复选框中获取信息

时间:2010-11-04 12:41:26

标签: android

我的报告包含5个问题(可以只有一个答案多项选择答案)。每个报告的问题都不同。因此,每次我生成问题和答案为RadioButtons(一个答案)或CheckBoxes(多选答案)......但现在我真的不知道如何保存这些答案(我想保存为_question_id_answer_id)。

如何将好_answer_id分配给_question_id ...

提前感谢您的帮助

2 个答案:

答案 0 :(得分:0)

我想您正在将RadioGroup用于一组互斥的RadioButtons?然后:

radioGroup.getCheckedRadioButtonId()  // gets Id of clicked RadioButton within group

对于CheckBox,您必须检查每个按钮:

checkBox.isChecked()

答案 1 :(得分:0)

尝试这样的事情:

public void saveAnswers() {
    LinearLayout root = (LinearLayout) findViewById(R.id.frame); //or whatever your root control is
    loopQuestions(root);
}

private void loopQuestions(ViewGroup parent) {
    for(int i = 0; i < parent.getChildCount(); i++) {
        View child = parent.getChildAt(i);
        if(child instanceof RadioGroup ) {
            //Support for RadioGroups
            RadioGroup radio = (RadioGroup)child;
            storeAnswer(radio.getId(), radio.getCheckedRadioButtonId());
        }
        else if(child instanceof CheckBox) {
            //Support for checkboxes
            CheckBox cb = (CheckBox)child;
            int answer = cb.isChecked() ? 1 : 0;
            storeAnswer(cb.getId(), answer);
        }
        else {
            //Support for other controls
        }

        if(child instanceof ViewGroup) {
            //Nested Q&A
            ViewGroup group = (ViewGroup)child;
            loopQuestions(group);
        }
    }
}

private void storeAnswer(int question, int answer) {
    //TODO: Store your answer to disk
}