Невозможно установить идентификатор для переключателей в ArrayAdapter с ListView - PullRequest
0 голосов
/ 21 марта 2019

[Пример проекта ссылка для скачивания]

У меня работает приложение-викторина для викторины.У меня есть несколько вопросов, и у каждого вопроса есть три ответа в виде трех радиокнопок внутри радиогруппы.Проблема в том, что когда я использую setId для переключателей, я заменяю ответы, поэтому на вопрос № 1 получаются ответы на вопросы № 5 и т. Д., Что делает все неправильно.если я не установил идентификатор для радио-кнопок, я получаю правильные ответы на все вопросы, но теперь проблема заключается в том, что, когда я отправляю ответ на вопрос, он также включает другой вопрос, потому что у радио-кнопок нет идентификаторов, которые можно поймать при прослушивании кнопки отправки.щелкните.

Я попытался снова задать ID, но та же проблема заменяет ответы между вопросами.Как я могу указать разные идентификаторы для каждой радиокнопки?Я попытался создать случайное число, но оно дублируется для первого скрытого вопроса при прокрутке вниз.

public class QuestionsAdapter extends ArrayAdapter<Questions> {

public QuestionsAdapter(Activity context, ArrayList<Questions> questions) {
    super(context, 0, questions);
}

private int t;
Random ran = new Random();
// Assumes max and min are non-negative.

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
    }
        //styling odd and even items
        if (position % 2 == 1) {
            listItemView.setBackgroundColor(getContext().getResources().getColor(R.color.odd));
        } else {
            listItemView.setBackgroundColor(getContext().getResources().getColor(R.color.even));
        }

        //used ViewHolder to prevent triggering position null issue
        final ViewHolder viewHolder = new ViewHolder();

        try {
            final Questions currentQuestion = getItem(position);

            String question = currentQuestion.getQuestionTitle();
            String option_1 = currentQuestion.getQuestionAnswer1();
            String option_2 = currentQuestion.getQuestionAnswer2();
            String option_3 = currentQuestion.getQuestionAnswer3();
            int q_id = currentQuestion.getQID();

            viewHolder.questionTextView = (TextView) listItemView.findViewById(R.id.q_text);
            viewHolder.questionTextView.setText(question);

            viewHolder.radioGroup = (RadioGroup) listItemView.findViewById(R.id.q_answers);

            viewHolder.firstAnswer = (RadioButton) listItemView.findViewById(R.id.q_option1);
            viewHolder.firstAnswer.setText(option_1);

            viewHolder.secondAnswer = (RadioButton) listItemView.findViewById(R.id.q_option2);
            viewHolder.secondAnswer.setText(option_2);

            viewHolder.thirdAnswer = (RadioButton) listItemView.findViewById(R.id.q_option3);
            viewHolder.thirdAnswer.setText(option_3);

            final TextView resultTextView = (TextView) listItemView.findViewById(R.id.result_text);

            final Button viewAnswer = (Button) listItemView.findViewById(R.id.view_answer_btn);
            viewAnswer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(viewHolder.radioGroup.getCheckedRadioButtonId()!=-1){

                        //getting checked radio button and save it's text in a string
                        int selectedAnswerId = viewHolder.radioGroup.getCheckedRadioButtonId();
                        View radioButton = viewHolder.radioGroup.findViewById(selectedAnswerId);
                        int radioId = viewHolder.radioGroup.indexOfChild(radioButton);
                        RadioButton btn = (RadioButton) viewHolder.radioGroup.getChildAt(radioId);
                        String selection = (String) btn.getText();

                        //displaying the empty result TextView
                        resultTextView.setVisibility(View.VISIBLE);

                        //if answer is correct (selection equals the answer in the array
                        if( selection == currentQuestion.getCorrect() ){

                            //increasing score by 1
                            MainActivity.score += 1;

                            //displaying the score
                            MainActivity.scoreTextView.setText(getContext().getResources().getString(R.string.score_is) +
                                    MainActivity.score + "/" + MainActivity.arraySize);

                            //displaying the result after submitting the answer of this question
                            resultTextView.setText(selection + " " + getContext().getResources().getString(R.string.correct));

                            //changing color of the result to green
                            resultTextView.setTextColor(getContext().getResources().getColor(R.color.green));
                        }
                        else{

                            //displaying the result after submitting the answer of this question
                            resultTextView.setText(getContext().getResources().getString(R.string.wrong_answer) + " " +
                                    currentQuestion.getCorrect());

                            //changing color of the result to red
                            resultTextView.setTextColor(getContext().getResources().getColor(R.color.red));
                        }

                        //hiding the button and RadioGroup of this question
                        viewHolder.radioGroup.setVisibility(View.GONE);
                        viewAnswer.setVisibility(View.GONE);
                    }
                    else{
                        Toast.makeText(getContext(),getContext().getResources().getString(R.string.Choose_answer_first),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    return listItemView;
}

  private class ViewHolder {
    TextView questionTextView;
    RadioGroup radioGroup;
    RadioButton firstAnswer, secondAnswer,thirdAnswer;
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...