Android片段问题的多个实例

时间:2016-02-01 14:59:00

标签: android android-fragments

我无法解决以下问题:

我正在制作一个小测验Android应用程序。我有一个QuizActivity和一个QuizFragment,我在活动中构建了一个QuizFragments列表:

questionFragments = new ArrayList<>();
questionFragments.add(QuestionFragment.newInstance(new Question("Amai menne ...",
        new ArrayList<Answer>() {{
            add(new Answer("Frak", false));
            add(new Answer("Jas", true));
            add(new Answer("Bernadette", false));
        }})));

questionFragments.add(QuestionFragment.newInstance(new Question("Question 2",
        new ArrayList<Answer>() {{
            add(new Answer("Answer 1", false));
            add(new Answer("Answer 2", true));
        }})));

enter image description here

我在活动中有一个替换当前QuestionFragment的方法:

private void showQuestion(int question) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.content_quiz_fl_question, questionFragments.get(question));
    transaction.commit();
}

QuestionActivity中的回调:

@Override
public void onCorrectAnswerSelected() {
    showQuestion(currentQuestion + 1);
}

在我的QuestionFragment中,我以编程方式构建RadioGroup(OnCreateView):

radioGroup = new RadioGroup(getContext());
radioGroup.setOrientation(RadioGroup.VERTICAL);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.BELOW, R.id.fragment_question_tv_title);
radioGroup.setLayoutParams(lp);

for (Answer answer : question.getAnswers()) {
    RadioButton radioButton = new RadioButton(getContext());
    radioButton.setText(answer.getAnswer());
    radioButton.setPadding(0, 30, 0, 30);
    radioGroup.addView(radioButton);
}

我在片段的按钮上有一个监听器:

verifyAnswer.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();

        if (question.getAnswers().get(checkedRadioButtonId - 1).isCorrect()) {
            //Correct
            handleSuccess();
        } else {
            //Incorrect
            handleFailure();
        }
    }
});

现在这是我遇到问题的地方,当我回答第一个问题时,一切都按计划进行,但当我回答第二个问题时,应用程序崩溃了。我能够在调试的帮助下查明问题。 我好像是RadioGroup&#34;记得&#34;以前问题的可能答案(在这种情况下,我从第二个问题中选择了第二个选项)。您可以在下面看到所选的radioButtonId为5,但我只有2个单选按钮:

enter image description here

我将不胜感激任何帮助!源代码:https://github.com/Jdruwe/ElineBirthday

1 个答案:

答案 0 :(得分:1)

显然,您需要执行以下操作才能获取所选RadioButton(How to get the selected index of a RadioGroup in Android)的索引:

int radioButtonID = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(radioButtonID);
int idx = radioGroup.indexOfChild(radioButton); 
相关问题