I found the solution but I still leave my question underneath. I used setBackgroundResource
instead of ContextCompat
, solution:
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
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));
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; 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.
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));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.