[英]Java: How to set context for ContextCompat in RecyclerView Adapter?
I found the solution but I still leave my question underneath. 我找到了解决方案,但是我仍然把我的问题放在下面。 I used
setBackgroundResource
instead of ContextCompat
, solution: 我使用
setBackgroundResource
而不是ContextCompat
解决方案:
holder.mTextPar.setBackgroundResource(R.drawable.border_box);
Original question: 原始问题:
I need to set my item element backgrounds with ContextCompat, but I don't know what to put to the context 我需要使用ContextCompat设置项目元素背景,但我不知道要在上下文中添加什么
This I tried: 我尝试过的
public Context context;
@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {
holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
}
When I open the Activity where this GameAdapter "works", the app instantly crashes and error report prefer to this line where I have this holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
当我打开该GameAdapter“工作”的活动时,应用程序立即崩溃,并且错误报告更喜欢此行所在的行
holder.mTextPar.setBackground(ContextCompat.getDrawable(context, R.drawable.border_box));
All answers telling you to take context as a parameter is wrong or redundant, you already have a way of getting context from your view: 所有答案都告诉您将上下文视为参数是错误的或多余的,您已经有了从视图中获取上下文的方法:
@Override
public void onBindViewHolder(@NonNull GameViewHolder holder, int position) {
Context context = holder.itemView.getContext();
}
It's unclear what adapter you are talking about, ArrayAdapter
, RecyclerView
adapter; 不清楚您在说什么适配器,
ArrayAdapter
, RecyclerView
适配器; please mention it; 请提及; also write more codes to help others understand what/where the context is needed.
还编写更多代码以帮助其他人了解上下文的需要/位置。 Generally if it's
RecyclerView
Adapter, the context will of views', eg itemView.getContext()
, if it's ArrayAdapter
, there's a getContext()
method. 通常,如果是
RecyclerView
Adapter,则视图的上下文将是这样,例如itemView.getContext()
;如果是ArrayAdapter
,则有一个getContext()
方法。
In your adapter constructor , add context as parameter. 在您的适配器构造函数中,将上下文添加为参数。
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.