Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:如何在RecyclerView适配器中设置ContextCompat的上下文?_Java_Android - Fatal编程技术网

Java:如何在RecyclerView适配器中设置ContextCompat的上下文?

Java:如何在RecyclerView适配器中设置ContextCompat的上下文?,java,android,Java,Android,我找到了解决办法,但我仍然把我的问题留在下面。 我使用了setBackgroundResource而不是ContextCompat, 解决方案: holder.mTextPar.setBackgroundResource(R.drawable.border_box); 原始问题: 我需要用ContextCompat设置我的item元素背景,但我不知道要将什么放到上下文中 我试过: public Context context; @Override public void onBindView

我找到了解决办法,但我仍然把我的问题留在下面。 我使用了
setBackgroundResource
而不是
ContextCompat
, 解决方案:

holder.mTextPar.setBackgroundResource(R.drawable.border_box);
原始问题:

我需要用ContextCompat设置我的item元素背景,但我不知道要将什么放到上下文中

我试过:

public Context context;

@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {

  holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
}

当我打开这个GameAdapter“工作”的活动时,应用程序会立即崩溃,错误报告更倾向于这一行,在这一行中我有这个
holder.mTextPar.setBackground(ContextCompat.getDrawable(context,R.drawable.border_box))

不清楚您所说的适配器是什么,
ArrayAdapter
RecyclerView
适配器;请提一下;还要编写更多代码,以帮助其他人理解上下文的内容/位置。通常,如果它是
RecyclerView
适配器,则上下文将是视图的一部分,例如
itemView.getContext()
,如果它是
ArrayAdapter
,则有一个
getContext()
方法。

在适配器构造函数中,添加上下文作为参数

public Context context;

public YourAdapterClass(Context context){
    this.context = context;
}

@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {
    holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
}

所有告诉您将上下文作为参数的答案都是错误的或多余的,您已经有了从视图中获取上下文的方法:

@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {
  Context context = holder.itemView.getContext(); 
}

Context contect在适配器中声明全局并使用“(Context.getDrawable(GameAdapter.this,R.drawable.border_box));”将上下文作为适配器的参数,然后使用它。我们不会保存它。我们只是从与我们一起设置适配器的视图中获取它。因此,如果视图将销毁,它将自动销毁。