I\'m trying to use picasso library to be able to load url to imageView, but I\'m not able to get the context
to use the picasso library correctly.
You can use like this view.getContext()
Example
holder.tv_room_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "", Toast.LENGTH_SHORT).show();
}
});
you can use this:
itemView.getContext()
If you are using Databinding on layout you can get the context
from holder
. An exemple below.
@Override
public void onBindViewHolder(@NonNull GenericViewHolder holder, int position) {
View currentView = holder.binding.getRoot().findViewById(R.id.cycle_count_manage_location_line_layout);// id of your root layout
currentView.setBackgroundColor(ContextCompat.getColor(holder.binding.getRoot().getContext(), R.color.light_green));
}
Short answer:
Context context;
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
context = recyclerView.getContext();
}
Explanation why other answers are not great:
Context
to the adapter is completely unnecessary, since RecyclerView
you can access it from inside the classContext
at ViewHolder
level means that you do it every time you bind or create a ViewHolder
. You duplicate operations.Activity
lifespan (which would be weird) then you already have a leak.View mView;
mView.getContext();
Create a constructor of FeedAdapter :
Context context; //global
public FeedAdapter(Context context)
{
this.context = context;
}
and in Activity
FeedAdapter obj = new FeedAdapter(this);