在 RecyclerView Adapter 中的 onBindViewHolder 中获取上下文

Nan*_*ncy 2 android

我试图在 RecyclerViewAdapter 中以编程方式创建复选框,但我不确定如何在 onBindViewHolder 中传递上下文。另外值得注意的是我使用了 4 个不同的 ViewHolders 类。

这是我要添加复选框的 ViewHolder 类,此代码位于onBindViewHolder

ViewHolderMulChoice viewHolderMulChoice = (ViewHolderMulChoice) holder;
viewHolderMulChoice.questionNumber.setText((position + 1) + ")");
viewHolderMulChoice.questionTitle.setText(current.getQuestion());
viewHolderMulChoice.questionInstructions.setText(current.getInstruction());
if (current.getOptional() == 1) {
    viewHolderMulChoice.questionOptional.setText("*");
} else {
    viewHolderMulChoice.questionOptional.setText("");
}

List<SurveyQuestionOptions> options = current.getSurvey_question_option();
for (SurveyQuestionOptions option: options) {
    CheckBox checkBox = new CheckBox(//context goes here);
    checkBox.setText(option.getOption());
    viewHolderMulChoice.options.addView(checkBox);
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*nth 10

您不必将上下文作为构造函数参数。每个视图都引用上下文

@Override
public void onBindViewHolder(@NonNull Holder holder, int i) {
     Context context = holder.itemview.getContext();
}
Run Code Online (Sandbox Code Playgroud)