Change recyclerview adapter items from own activity after clicking on button inside adapter

huangapple go评论64阅读模式
英文:

Change recyclerview adapter items from own activity after clicking on button inside adapter

问题

public class QuestionRecyclerAdapter extends RecyclerView.Adapter<QuestionRecyclerAdapter.ViewHolder> {

    // ... (Other parts of the adapter code)

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (position != questionHolders.size()) {
            // ... (Setting up question data and radio button actions)

            if (onQuestionAnswerSelect != null) {
                holder.questionRadioGroup.setOnCheckedChangeListener((v, i) -> {
                    RadioButton rBtnSelected = holder.questionRadioGroup.findViewById(holder.questionRadioGroup.getCheckedRadioButtonId());
                    int selectedRadioIndex = holder.questionRadioGroup.indexOfChild(rBtnSelected) + 1;

                    if (selectedRadioIndex == questionHolders.get(position).getQuestionModel().getCorrectNumber()) {
                        onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), true);
                    } else {
                        onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), false);
                    }
                });
            }
        } else {
            holder.btnConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onConfirmButtonClicked != null)
                        onConfirmButtonClicked.onConfirmClicked();
                }
            });
        }
    }

    // ... (Other parts of the adapter code)

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView txtQuestion;
        public RadioGroup questionRadioGroup;
        public RadioButton rBtnAnswer1;
        public RadioButton rBtnAnswer2;
        public RadioButton rBtnAnswer3;
        public RadioButton rBtnAnswer4;
        public Button btnConfirm;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txtQuestion = itemView.findViewById(R.id.txtQuestion);
            questionRadioGroup = itemView.findViewById(R.id.questionRadioGroup);
            rBtnAnswer1 = itemView.findViewById(R.id.rBtnAnswer1);
            rBtnAnswer2 = itemView.findViewById(R.id.rBtnAnswer2);
            rBtnAnswer3 = itemView.findViewById(R.id.rBtnAnswer3);
            rBtnAnswer4 = itemView.findViewById(R.id.rBtnAnswer4);
            btnConfirm = itemView.findViewById(R.id.btnConfirm);
        }
    }
}

public class QuizActivity extends AppCompatActivity {

    // ... (Other parts of the activity code)

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        questionRecyclerView = findViewById(R.id.questionRecyclerView);
        questionDatabaseHelper = new QuestionDatabaseHelper(this);

        int selectedId = getIntent().getIntExtra(Constants.SELECTED_ID, 0);
        score = 0;

        List<QuestionHolder> questionHolders = questionDatabaseHelper.getAllQuestionHoldersById(selectedId);
        adapter = new QuestionRecyclerAdapter(this, questionHolders);
        questionRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        questionRecyclerView.setAdapter(adapter);

        adapter.setOnQuestionAnswerSelect(new OnQuestionAnswerSelect() {
            @Override
            public void onAnswerSelected(int questionNumber, boolean isCorrect) {
                answeredRecords.put(questionNumber, isCorrect);
            }
        });
        adapter.setOnConfirmButtonClicked(new OnConfirmButtonClicked() {
            @Override
            public void onConfirmClicked() {
                score = 0;
                for (Map.Entry<Integer, Boolean> item : answeredRecords.entrySet()) {
                    if (item.getValue())
                        score++;
                }
                Log.e("THE SCORE IS ", String.valueOf(score));
            }
        });
    }

    // ... (Other parts of the activity code)

    private void displayRecords() {
        for (Map.Entry<Integer, Boolean> item : answeredRecords.entrySet()) {
            Log.e("AAA", item.getKey() + " : " + item.getValue());
        }
    }
}

(Note: This code is a direct translation of the provided Java code into Chinese. If you need any additional assistance or explanation, feel free to ask.)

英文:

I built a simple quiz app with sqlite database
There is some quiz headers and into this quiz headers we have some questions that show by recycler view. All questions have one question title and 4 answers and one correct answer. user chooses the radio button answers and after that click on confirm button that is located as item at the bottom of recycler view.
I can catch the correct answer with a simple way and send it to the activity with an interface. But i want to show the correct and wrong answers with changing the radio buttons color but I can't create another method and change the view holder items because I can't access to the view holders outside of 'onBindViewHolder' method . I can handle this with another adapter . I mean I can create a fake adapter that just show answers . Is it a right way ?

This is my code. It's a little messy. Sorry about that

public class QuestionRecyclerAdapter extends RecyclerView.Adapter&lt;QuestionRecyclerAdapter.ViewHolder&gt; {
private Context context;
private List&lt;QuestionHolder&gt; questionHolders;
private OnQuestionAnswerSelect onQuestionAnswerSelect;
private OnConfirmButtonClicked onConfirmButtonClicked;
public QuestionRecyclerAdapter(Context context, List&lt;QuestionHolder&gt; questionHolders) {
this.context = context;
this.questionHolders = questionHolders;
}
public void setOnQuestionAnswerSelect(OnQuestionAnswerSelect onQuestionAnswerSelect) {
this.onQuestionAnswerSelect = onQuestionAnswerSelect;
}
public void setOnConfirmButtonClicked(OnConfirmButtonClicked onConfirmButtonClicked){
this.onConfirmButtonClicked = onConfirmButtonClicked;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView;
if (viewType == R.layout.question_item)
itemView = LayoutInflater.from(context).inflate(R.layout.question_item, parent, false);
else
itemView = LayoutInflater.from(context).inflate(R.layout.question_recycler_confirm_button, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
if (position != questionHolders.size()) {
QuestionModel currentModel = questionHolders.get(position).getQuestionModel();
holder.txtQuestion.setText(currentModel.getTitle());
holder.rBtnAnswer1.setText(currentModel.getOption1());
holder.rBtnAnswer2.setText(currentModel.getOption2());
holder.rBtnAnswer3.setText(currentModel.getOption3());
holder.rBtnAnswer4.setText(currentModel.getOption4());
if (onQuestionAnswerSelect != null) {
holder.questionRadioGroup.setOnCheckedChangeListener((v, i) -&gt; {
RadioButton rBtnSelected = holder.questionRadioGroup.findViewById(holder.questionRadioGroup.getCheckedRadioButtonId());
int selectedRadioIndex = holder.questionRadioGroup.indexOfChild(rBtnSelected) + 1;
if (selectedRadioIndex == questionHolders.get(position).getQuestionModel().getCorrectNumber()) {
onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), true);
} else {
onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), false);
}
});
}
}else {
holder.btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onConfirmButtonClicked != null)
onConfirmButtonClicked.onConfirmClicked();
}
});
}
}
@Override
public int getItemCount() {
return questionHolders.size() + 1;
}
@Override
public int getItemViewType(int position) {
return (position == questionHolders.size()) ? R.layout.question_recycler_confirm_button : R.layout.question_item;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtQuestion;
public RadioGroup questionRadioGroup;
public RadioButton rBtnAnswer1;
public RadioButton rBtnAnswer2;
public RadioButton rBtnAnswer3;
public RadioButton rBtnAnswer4;
public Button btnConfirm;
public ViewHolder(@NonNull View itemView) {
super(itemView);
txtQuestion = itemView.findViewById(R.id.txtQuestion);
questionRadioGroup = itemView.findViewById(R.id.questionRadioGroup);
rBtnAnswer1 = itemView.findViewById(R.id.rBtnAnswer1);
rBtnAnswer2 = itemView.findViewById(R.id.rBtnAnswer2);
rBtnAnswer3 = itemView.findViewById(R.id.rBtnAnswer3);
rBtnAnswer4 = itemView.findViewById(R.id.rBtnAnswer4);
btnConfirm = itemView.findViewById(R.id.btnConfirm);
}
}

}

public class QuizActivity extends AppCompatActivity {
RecyclerView questionRecyclerView ;
QuestionRecyclerAdapter adapter ;
QuestionDatabaseHelper questionDatabaseHelper ;
Map&lt;Integer,Boolean&gt; answeredRecords = new HashMap&lt;&gt;();
int score ;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionRecyclerView = findViewById(R.id.questionRecyclerView);
questionDatabaseHelper = new QuestionDatabaseHelper(this);
int selectedId = getIntent().getIntExtra(Constants.SELECTED_ID,0);
score = 0 ;
List&lt;QuestionHolder&gt; questionHolders = questionDatabaseHelper.getAllQuestionHoldersById(selectedId);
adapter = new QuestionRecyclerAdapter(this,questionHolders);
questionRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
questionRecyclerView.setAdapter(adapter);
adapter.setOnQuestionAnswerSelect(new OnQuestionAnswerSelect() {
@Override
public void onAnswerSelected(int questionNumber, boolean isCorrect) {
answeredRecords.put(questionNumber,isCorrect);
}
});
adapter.setOnConfirmButtonClicked(new OnConfirmButtonClicked() {
@Override
public void onConfirmClicked() {
score = 0 ;
for(Map.Entry&lt;Integer,Boolean&gt; item : answeredRecords.entrySet()){
if (item.getValue())
score++;
}
Log.e(&quot;THE SCORE IS &quot;, String.valueOf(score));
}
});
}
private void displayRecords(){
for(Map.Entry&lt;Integer,Boolean&gt; item : answeredRecords.entrySet()){
Log.e(&quot;AAA&quot;,item.getKey() + &quot; : &quot; + item.getValue());
}
}

}

答案1

得分: 2

在适配器中创建一个函数,并通过调用该函数将 holder 发送到活动中。
首先创建一个名为 holder1 的视图持有者。

ViewHolder holder1;

然后在 onBindViewHolder 方法中添加以下内容:

holder1 = holder;
public ViewHolder getHolder(){
return holder1;
}

现在你可以在你的活动中像这样使用它:

adapter.getHolder.rBtnAnswer1.setBackgroundColor(Color.parseColor("#FFFFFF")); //这是一个示例。
英文:

Make a function in adapter and send holder to activity by calling that function.
first make viewholder named holder1.

ViewHolder holder1;

then at the onBindViewHolder method add this:

holder1 = holder;
public ViewHolder getHolder(){
return holder1;
}

now you can use it in your Activity like this:

adapter.getHolder.rBtnAnswer1.setBackgroundColor(Color.parseColor(&quot;#FFFFFF&quot;)); //this is a example.

huangapple
  • 本文由 发表于 2020年5月29日 12:57:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/62078995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定