Android单选按钮正在更改片段之间的ID

时间:2014-12-09 22:22:44

标签: android radio-button persistence

我为我正在构建的调查应用程序提供了一组动态创建的片段。在每个创建的片段中都是生成的问题,并动态创建用于多选答案的单选按钮。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout containing a title and body text.
    ViewGroup rootView = (ViewGroup) inflater
            .inflate(R.layout.fragment_survey_page, container, false);
    ((TextView) rootView.findViewById(R.id.aQuestion)).setText(question);

    // create radio buttons, Set the answers
    rGroup = ((RadioGroup) rootView.findViewById(R.id.radiogroup));
    for (int j = 0; j < answers.size(); j++) {
        HashMap answer = (HashMap) answers.get(j);
        RadioButton rdbtn = new RadioButton(getActivity(),null,0,R.style.rButton);
        rdbtn.setText(answer.get("aName").toString());
        rGroup.addView(rdbtn);
    }

    // and add a listener
    rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId){
            RadioButton checkedRadioButton = (RadioButton) getActivity().findViewById(checkedId);
            String text = checkedRadioButton.getText().toString();
            savedChecked = checkedId;
            try {
                Log.d("RADIO",""+rGroup.getCheckedRadioButtonId());
                questions.put("answer", text);
                listener.putAnswer(questions);
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
return rootView;
}

选中此选项后,会创建一个包含新问题和一组可能答案的新片段。

如何让单选按钮的状态保持在片段之间?我已尝试将其ID存储在系统首选项中,但当您导航回ID时会发生更改。假设它从1开始,你离开,标记另一个单选按钮,导航回来,ID(1)是不同的。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我能够通过向具有设定值的单选按钮添加Id来获得值。

rGroup = ((RadioGroup) rootView.findViewById(R.id.radiogroup));
    for (int j = 0; j < answers.size(); j++) {
        HashMap answer = (HashMap) answers.get(j);
        RadioButton rdbtn = new RadioButton(getActivity(),null,0,R.style.rButton);
        rdbtn.setText(answer.get("aName").toString());
        rdbtn.setId(Integer.parseInt(answer.get("aId").toString()));
        rGroup.addView(rdbtn);
    }