繁体   English   中英

Java:如何在RecyclerView Adapter中为ContextCompat设置上下文?

[英]Java: How to set context for ContextCompat in RecyclerView Adapter?

我找到了解决方案,但是我仍然把我的问题放在下面。 我使用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“工作”的活动时,应用程序立即崩溃,并且错误报告更喜欢此行所在的行holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));

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

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

不清楚您在说什么适配器, ArrayAdapterRecyclerView适配器; 请提及; 还编写更多代码以帮助其他人了解上下文的需要/位置。 通常,如果是RecyclerView Adapter,则视图的上下文将是这样,例如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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM