我找到了解决方案,但我仍然将我的问题留在下面。
我使用 setBackgroundResource
而不是 ContextCompat
,
解决办法:
holder.mTextPar.setBackgroundResource(R.drawable.border_box);
原始问题:
我需要使用 ContextCompat 设置项目元素背景,但我不知道要在上下文中添加什么内容
我尝试过:
public Context context;
@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {
holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
}
当我打开此 GameAdapter“工作”的 Activity 时,应用程序立即崩溃,并且错误报告更喜欢我有此 holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box) 的行));
最佳答案
所有告诉您将上下文作为参数的答案都是错误或多余的,您已经有一种从 View 中获取上下文的方法:
@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {
Context context = holder.itemView.getContext();
}
关于Java:如何在 RecyclerView Adapter 中设置 ContextCompat 的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57229299/