我正在开发测验应用程序。其中有两个用于上一个问题和下一个问题的按钮。我想做的是当用户从选项中选择答案(对于选项有 4 个单选按钮)并尝试下一个问题但是如果用户当时想查看上一个问题应启用用户先前选择的相同单选按钮。为此,我使用共享首选项来存储选定的单选按钮 ID。 这是我的代码: 点击下一步按钮:
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int radioSelected = radioGroup.getCheckedRadioButtonId();
int userSelection = getSelectedAnswer(radioSelected);
sharedPreferences=getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("Ans",userSelection);
editor.commit();
int correctAnswerForQuestion =firstQuestion.getCorrectAnswer();
if(userSelection == correctAnswerForQuestion)
{
Toast.makeText(getApplicationContext(),"Correct Answer",Toast.LENGTH_LONG).show();
currentQuizQuestion++;
if(currentQuizQuestion>=quizCount)
{
Toast.makeText(getApplicationContext(),"End of quiz",Toast.LENGTH_LONG).show();
return;
}
else
{
firstQuestion=parsedObject.get(currentQuizQuestion);
txtquestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers=firstQuestion.getAnswers().split(",");
uncheckedRadioButton();
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
}
else
{
Toast.makeText(getApplicationContext(),"You choose wrong answer",Toast.LENGTH_LONG).show();
currentQuizQuestion++;
firstQuestion=parsedObject.get(currentQuizQuestion);
txtquestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers=firstQuestion.getAnswers().split(",");
uncheckedRadioButton();
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
}
});
对于上一个按钮:
previousButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentQuizQuestion--;
if(currentQuizQuestion<0)
{
return;
}
checkedRadioButton();
firstQuestion=parsedObject.get(currentQuizQuestion);
txtquestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers=firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
});
JSON_DATA_WEB_CALL();
}
private void checkedRadioButton() {
int ans=1;
int ans1=sharedPreferences.getInt("Ans",ans);
if(optionOne.getId()==ans1)
{
optionOne.setChecked(true);
}
}
请帮帮我。非常感谢。
最佳答案
为每个单选按钮选项添加标签 optionOne.setTag("answer_tag", "one")。 存储选择的标签,并将 radiobuttons.getTag("answer_tag) 与存储的标签进行比较。
关于android - 如何根据保存在android studio共享首选项中的单选按钮id启用单选组的特定单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411490/