Я пишу код всего пару месяцев, и я все еще довольно новичок во многих техниках, но я работаю над тестом по математике для моего 5-летнего сына.Я пытался в нескольких разных «играх» играть и бросать вызов самому себе.Вчера я закончил испытание времени и матч по шаблону на прошлой неделе, но теперь я застрял в текущей игре, которая является вызовом уровней.Игрок должен ответить на 10 вопросов правильно, чтобы перейти на следующий уровень (где вопросы становятся сложнее).
Я использую RecyclerView для создания вопросов.Каждый вопрос заполнен случайными целыми числами, и возможные ответы можно выбрать как RadioButtons.
![screenshot](https://i.imgur.com/4qbkyh8.png)
До сих пор я был в состоянии выяснить, как добавить форматирование и обновить ViewHolder, но теперь я застрял при попытке создать метод в моем фрагменте, чтобы проверить все ответы на вопросы.Я полагаю, что это должно быть сделано во фрагменте, поскольку во фрагменте я определяю, сколько вопросов создавать, и где генерируются случайные числа и передаются в ArrayList, который адаптер Recycler использует для обновления держателя представления.
Я надеюсь, что я достаточно хорошо объясняю себя, поэтому мой вопрос заключается в том, как я могу проверить, что все радиогруппы соответствуют следующим параметрам:
- Имеет выбранную кнопку радио
- Ответправильно (если на них дан неправильный ответ, они не перейдут на следующий уровень, а вместо этого получат новый набор вопросов той же сложности.
Вот мой класс фрагментов:
public class FragmentLevelChallenge extends Fragment{
public static final String TAG = "LevelChallengeFragment";
RecyclerView recyclerView;
RVAdapterMulti adapterMulti;
private List<multiquestion> QuestionsMulti;
int firstDig;
int secondDig;
int correctAnswer;
int incorrectOne;
int incorrectTwo;
int incorrectThree;
int thisPosition;
int selectedAnswers;
int questionsAnswered;
//levelChallenge defines the current challenge level
int levelChallenge;
int maxBound = 10;
int minBound = 1;
int adjustBound = 1;
RadioGroup radioGroupRecycler;
public static FragmentLevelChallenge newInstance() {
FragmentLevelChallenge fragment = new FragmentLevelChallenge();
return fragment;
}
@Override
public void onCreate (Bundle savedInstanceState) {super.onCreate(savedInstanceState);}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_level_challenge, container, false);
levelChallenge = 1;
QuestionsMulti = new ArrayList<>();
recyclerView = view.findViewById(R.id.recycler_view_display_multi);
radioGroupRecycler = view.findViewById(R.id.radio_group_multi);
LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(layoutManager);
TextView levelsText = view.findViewById(R.id.level_challenge);
levelsText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
initializeRecyclerAdapter();
createQuestionBatch();
return view;
}
private void createQuestionBatch() {
//Integer values to define the minimum, maximum and adjustment for random integers
if (selectedAnswers == 5) {
levelChallenge++;
}
//Checks the current level to determine the boundaries for difficulty of random integers
switch (levelChallenge) {
case 1: //If level 1 (bounds 10,1,1)
maxBound = 10;
minBound = 1;
adjustBound = 1;
break;
case 2: //If level 2 (bounds 20,1,4)
maxBound = 20;
minBound = 1;
adjustBound = 4;
break;
case 3: //If level 3 (bounds 25,10,5)
maxBound = 25;
minBound = 10;
adjustBound = 5;
break;
case 4: //If level 4 (bounds 30,10,7)
maxBound = 30;
minBound = 10;
adjustBound = 7;
break;
case 5: //If level 5 (bounds 50,10,9)
maxBound = 50;
minBound = 10;
adjustBound = 9;
break;
case 6: //If level 6 (bounds 75,10,15)
maxBound = 75;
minBound = 10;
adjustBound = 15;
break;
case 7: //If level 7 (bounds 100,10,18)
maxBound = 100;
minBound = 10;
adjustBound = 18;
break;
//If level 8 (bounds random integers?)
}
//Creates the random integers for math functions
int questionsToFillRecycler = 5;
for (int i = 0; i < questionsToFillRecycler; i++) {
final Random r = new Random();
Random position = new Random();
thisPosition = position.nextInt(4 - 1) + 1;
//Creates the array list for incorrect answers
firstDig = r.nextInt(maxBound - minBound) + adjustBound;
secondDig = r.nextInt(maxBound - minBound) + adjustBound;
if (firstDig < secondDig) {
correctAnswer = secondDig - firstDig;
incorrectOne = secondDig - firstDig - 1;
incorrectTwo = secondDig - firstDig + 2;
incorrectThree = (secondDig + firstDig) - 2;
} else {
correctAnswer = firstDig + secondDig;
incorrectOne = secondDig + firstDig - 2;
incorrectTwo = secondDig + firstDig + 1;
incorrectThree = (firstDig - secondDig) + 3;
}
//Convert integer to string values
String firstNumber = String.valueOf(firstDig);
String secondNumber = String.valueOf(secondDig);
String firstIncorrect = String.valueOf(incorrectOne);
String secondIncorrect = String.valueOf(incorrectTwo);
String thirdIncorrect = String.valueOf(incorrectThree);
String correct = String.valueOf(correctAnswer);
List<String> answers = new Vector<>();
answers.add(correct);
answers.add(firstIncorrect);
answers.add(secondIncorrect);
answers.add(thirdIncorrect);
Collections.shuffle(answers);
if (firstDig < secondDig) {
//Checks if 1st integer is less than 2nd integer
QuestionsMulti.add(new multiquestion(secondNumber, firstNumber, answers.get(0), "-", answers.get(1), answers.get(2), answers.get(3)));
} else if (firstDig > secondDig) {
//Checks if 1st integer is greater than 2nd integer
QuestionsMulti.add(new multiquestion(secondNumber, firstNumber, answers.get(0), "+", answers.get(1), answers.get(2), answers.get(3)));
} else {
//Checks if 1st integer is greater than 2nd integer
QuestionsMulti.add(new multiquestion(secondNumber, firstNumber, answers.get(0), "+", answers.get(1), answers.get(2), answers.get(3)));
}
//Updates the RecyclerView Adapter
adapterMulti.notifyDataSetChanged();
}
}
private void initializeRecyclerAdapter() {
adapterMulti = new RVAdapterMulti(QuestionsMulti);
recyclerView.setAdapter(adapterMulti);
}
}
А вот мой RecyclerAdapter:
public class RVAdapterMulti extends RecyclerView.Adapter<RVAdapterMulti.ViewHolder> {
private static String TAG = "RadioMultiAdapter";
private LayoutInflater inflater;
private List<multiquestion> QuestionsMulti;
private int questionsAnswered;
private AdapterView.OnItemSelectedListener onSelect;
public RVAdapterMulti(List<multiquestion> QuestionMulti) {
this.QuestionsMulti = QuestionMulti;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_multi, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
multiquestion currentQuestion = QuestionsMulti.get(position);
holder.setFirstDigit(currentQuestion.firstNumber);
holder.setSecondDigit(currentQuestion.secondNumber);
holder.setMathFunction(currentQuestion.mathFunc);
holder.setOptions(currentQuestion, position);
}
@Override
public int getItemCount() {
if (QuestionsMulti == null) {
return 0;
} else {
return QuestionsMulti.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayoutContainer;
private TextView firstDigitView;
private TextView secondDigitView;
private TextView mathFunctionView;
private TextView mathAnswerView;
private RadioGroup radioGroupOptions;
private RadioButton radioButtonOne, radioButtonTwo;
private RadioButton radioButtonThree, radioButtonFour;
public ViewHolder(View itemView) {
super(itemView);
firstDigitView = itemView.findViewById(R.id.first_digit);
secondDigitView = itemView.findViewById(R.id.second_digit);
mathFunctionView = itemView.findViewById(R.id.math_function);
mathAnswerView = itemView.findViewById(R.id.math_answer);
radioGroupOptions = itemView.findViewById(R.id.radio_group_multi);
radioButtonOne = itemView.findViewById(R.id.radio_button_one);
radioButtonTwo = itemView.findViewById(R.id.radio_button_two);
radioButtonThree = itemView.findViewById(R.id.radio_button_three);
radioButtonFour = itemView.findViewById(R.id.radio_button_four);
}
public void setFirstDigit(String firstDigit) {
firstDigitView.setText(firstDigit);
}
public void setSecondDigit(String secondDigit) {
secondDigitView.setText(secondDigit);
}
public void setMathFunction(String mathFunction) {
mathFunctionView.setText(mathFunction);
}
public void setOptions(final multiquestion question, int position) {
radioGroupOptions.setTag(position);
radioButtonOne.setText(question.correct);
radioButtonTwo.setText(question.incorrectOne);
radioButtonThree.setText(question.incorrectTwo);
radioButtonFour.setText(question.incorrectThree);
if (question.mathFunc.equals("+")) {
question.correctSolution = Integer.parseInt(question.firstNumber) + Integer.parseInt(question.secondNumber);
} else {
question.correctSolution = Integer.parseInt(question.firstNumber) - Integer.parseInt(question.secondNumber);
}
if(question.isAnswered) {
radioGroupOptions.check(question.checkedId);
} else {
radioGroupOptions.check(-1);
}
radioGroupOptions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int pos = (int) group.getTag();
multiquestion que = QuestionsMulti.get(pos);
que.isAnswered = true;
que.checkedId = checkedId;
radioGroupOptions.setClickable(false);
radioButtonOne.setClickable(false);
radioButtonTwo.setClickable(false);
radioButtonThree.setClickable(false);
radioButtonFour.setClickable(false);
questionsAnswered = questionsAnswered + 1;
mathAnswerView.setText(String.valueOf(question.correctSolution));
String radioOneText = String.valueOf(radioButtonOne.getText());
String radioTwoText = String.valueOf(radioButtonTwo.getText());
String radioThreeText = String.valueOf(radioButtonThree.getText());
String radioFourText = String.valueOf(radioButtonFour.getText());
switch (que.checkedId) {
case R.id.radio_button_one:
if(radioOneText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
case R.id.radio_button_two:
if(radioTwoText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
case R.id.radio_button_three:
if(radioThreeText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
case R.id.radio_button_four:
if(radioFourText.equals(String.valueOf(question.correctSolution))) {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorCorrect));
} else {
mathAnswerView.setTextColor(group.getResources().getColor(R.color.colorIncorrect));
}
break;
}
}
});
}
}
}
Любая помощь будет принята с благодарностью.