Android RecyclerView 适配器:在当前项目视图的点击侦听器中更新已绘制的项目视图

Android RecyclerView Adapter : update already drawn item view in the click listener for current itemview

所以我有一个测验应用程序,我在其中向用户展示了一个问题和四个选项。 4 个选项在 RecyclerView 中给出,因此我将 4 个选项(作为字符串 ArrayList)和正确答案(字符串)传递给 RecyclerView 适配器构造函数。 现在,如果选择的答案是正确的 itemView 设置为绿色,如果错误则设置为红色(到目前为止工作正常)。

我的问题是

when I press the wrong answer I have to set the background color of the itemview(already drawn) with correct answer to turn green along with the selected wrong answer turning red

查看下面我的代码

@Override
public void onBindViewHolder(final OptionsAdapter.ViewHolder viewHolder, final int i) {
    viewHolder.tv_name.setText(option.get(i));
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (option.get(i).equals(correct)){
                Toast.makeText(context,"CORRECT ANSWER :)",Toast.LENGTH_SHORT).show();
                viewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.correctAnswer));
            } else {
                Toast.makeText(context,"SORRY INCORRECT ANSWER :(",Toast.LENGTH_SHORT).show();
                viewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.wrongAnswer));
            }
        }
    });

}

在我的 onBindViewHolder 的上述片段中,数组列表 option 有 4 个选项,字符串 correct 是正确答案。

点击错误答案后如何将正确答案变为绿色?

下图显示了点击错误答案时我的预期

将这些方法添加到您的模型中 class:

private boolean isSelected;

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}

在您的适配器上添加此代码 onClick

if (mArrayList.get(position).isSelected()) {
    mArrayList.get(position).setSelected(false);
} else {
    mArrayList.get(position).setSelected(true);
}
notifyItemChanged(position);