Проверьте состояние переключателей в Recycle View Adapter и внесите в него изменения из MainActivity. - PullRequest
0 голосов
/ 26 сентября 2018

В моем методе MainActivity необходимо изменить checkAnswer и showSolution, поскольку я добавил адаптер RecycleView в проект и переместил все элементы представления в QuestionAdapter.Я не понимаю, как я должен проверить состояние переключателей rbGroup с помощью isChecked в QuestionAdapter и передать его идентификатор в MainActivity.Я пытался проверить это: Radiogroup in recyclerview , но мне все еще неясно, какие шаги мне следует предпринять дальше.Может ли кто-нибудь дать мне базовые инструкции, какие шаги следует предпринять для изменения моего проекта с этого момента.Все еще не могу найти ответ или учебник для обработки списка переключателей в представлении Recycle.Как проверить статус переключателя с помощью интерфейса из MainActivity?

Сделано несколько обновлений, как было предложено.Не понимаю, как я должен изменить метод showSolution.

public class MainActivity extends AppCompatActivity {

public QuestionAdapter adapter;
public ArrayList<Question> questionList;
private int questionCountTotal;
private long backPressedTime;
private int score;
private int questionCounter;
private Button btnConfirmNext;
private boolean answered;
private Question currentQuestion;
private TextView tvQuestion, tvScore, tvQuestionCount, tvCountdown;
public QuizDbHelper dbHelper;
RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnConfirmNext = findViewById(R.id.confirm_button);
    tvCountdown = findViewById(R.id.count_down);
    tvScore = findViewById(R.id.text_view_score);

    recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setNestedScrollingEnabled(false);
    recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
    questionList = new ArrayList<>();
    adapter = new QuestionAdapter(this, questionList);

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 1);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);

    dbHelper = new QuizDbHelper(this);
    questionList = dbHelper.getAllQuestions();
    questionCountTotal = questionList.size();
    Collections.shuffle(questionList);

        prepareQuestion();

    btnConfirmNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            checkAnswer();
        }
    });

}


private void prepareQuestion() {
    adapter = new QuestionAdapter(getApplicationContext(), questionList);
    recyclerView.setAdapter(adapter);
    if (questionCounter < questionCountTotal) {
        currentQuestion = questionList.get(questionCounter);

        answered = false;
        btnConfirmNext.setText("Confirm");

    } else {
        finishQuiz();
    }
}


//How should I handle it in onbindViewHolder

private void checkAnswer() {
    answered = true;
    countDownTimer.cancel();
    RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
    int answerNb = rbGroup.indexOfChild(rbSelected) + 1;

    if (answerNb == currentQuestion.getAnswerNB()) {
        score++;
        tvScore.setText("Score: " + score);
    }
    showSolution();
}

//How should I change state of the items in recycle view

private void showSolution() {
    rb1.setTextColor(Color.RED);
    rb2.setTextColor(Color.RED);
    rb3.setTextColor(Color.RED);
    rb4.setTextColor(Color.RED);

    switch (currentQuestion.getAnswerNB()) {
        case 1:
            rb1.setTextColor(Color.GREEN);
            break;
        case 2:
            rb2.setTextColor(Color.GREEN);
            break;
        case 3:
            rb3.setTextColor(Color.GREEN);
            break;
        case 4:
            rb4.setTextColor(Color.GREEN);
            break;
    }

    btnConfirmNext.setText("Finish");

}

QuestionAdapter

public class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.MyViewHolder> {

public ArrayList<Question> questionList;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView tvQuestion, tvScore, tvQuestionCount, tvCountdown;
    public RadioGroup rbGroup;
    public RadioButton rb1, rb2, rb3, rb4;



    public MyViewHolder(View view) {
        super(view);
        tvQuestion = view.findViewById(R.id.question);
        rbGroup = view.findViewById(R.id.radiog_group);
        rb1 = view.findViewById(R.id.radio_button1);
        rb2 = view.findViewById(R.id.radio_button2);
        rb3 = view.findViewById(R.id.radio_button3);
        rb4 = view.findViewById(R.id.radio_button4);
    }
}


public QuestionAdapter(Context mContext, ArrayList<Question> questionList) {
    this.questionList = questionList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_card, parent, false);


    return new MyViewHolder(itemView);
}

@NonNull
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    final Question question = questionList.get(position);
    holder.tvQuestion.setText(question.getQuestion());
    holder.rb1.setText(question.getOption1());
    holder.rb2.setText(question.getOption2());
    holder.rb3.setText(question.getOption3());
    holder.rb4.setText(question.getOption4());

    holder.rbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {

// How can I handle Check status here and pass it to main activity?

        }
    });
}

@Override
public int getItemCount() {
    return questionList.size();
}
}

ОБНОВЛЕНИЕ. После добавления интерфейса в мой QuestionAdapter и применения изменений в конструкторе и другихчасти, мой checkAnswer в MainActivity выглядит следующим образом

    private void checkAnswer() {
    answered = true;
    countDownTimer.cancel();
    adapter = new QuestionAdapter(getApplicationContext(), questionList, new QuestionAdapter.OnItemListener() {
        @Override
        public void onItemSelect(int position) {
           if (position+1==currentQuestion.getAnswerNB()){
               score++;
               tvScore.setText("Score: " + score);
           }
        }
        });
    showSolution();
}

Что мне теперь делать с моим методом showSolution?Кажется, что после checkAnswer я должен отправить информацию обратно в QuestionAdapter и сделать там setTextColor.Возможно, я ошибся ...

MainActivity

Ответы [ 2 ]

0 голосов
/ 29 сентября 2018

вы можете сделать это с помощью интерфейса.

создайте интерфейс, подобный следующему:

public interface OnItemListener {
    public void onItemSelect(int position);
}

, затем в адаптере измените конструктор следующим образом:

  QuestionAdapter(Context mContext, ArrayList<Question> questionList, OnItemListener 
  onItemListener) {
        this.onItemListener = onItemListener;
        this.questionList = questionList;
    }

и добавьте эту строку в свой onCheckedChangeListener

            onItemListener.onItemSelect(position);

вот так:

holder.rbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {

        // How can I handle Check status here and pass it to main activity?
        onItemListener.onItemSelect(position);
        }
    });

затем в своей деятельности добавьте это, где вы определяете адаптер (это еще один способ определения адаптера, вы также можете использовать свой собственный способ, просто не забудьте добавить интерфейсвот так (новый OnItemListener ...)):

 dbHelper = new QuizDbHelper(getApplicationContext(), questionList, new 
 OnItemListener({

            @Override
            public void onItemSelect(int position) {
             // handle your check state of adapter item here
            }

        });
0 голосов
/ 26 сентября 2018

Возможно, вы захотите ознакомиться с приведенной ниже статьей, которую я написал для обработки кликов из адаптера и делегирования их операции или фрагменту

https://medium.com/@pithadiyamitesh/adaptercallback-for-handling-item-clicks-on-list-items-in-android-4f731d7d0094

...