开发者

Getting information from RadioButtons and Checkboxes

I have report which consists of 5 questions (there can be only one answer or multiple choice answer). Question are different for each report. So everytime I generate questions and answers as RadioButtons (one answer) or Ch开发者_如何转开发eckBoxes (multiple choice answer)...But now I really don't know how to save those answers (I'd like to save to it as _question_id, _answer_id).

How can I assign good _answer_id, to _question_id...

Thanks for help in advance


Try something like this:

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
}


I suppose you are using RadioGroup for a group of mutually exclusive RadioButtons? Then:

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

for CheckBox you must check for every button:

checkBox.isChecked()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜