Home » Android » android – How can I use getResources inside of onBindViewHolder()?

android – How can I use getResources inside of onBindViewHolder()?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have this method, and I want to use getResources() inside it:

 public void onBindViewHolder(ViewHolder viewHolder, int i) {

        viewHolder.itemTitle.setText(titles[i]);
        viewHolder.itemImage.setImageResource(images[i]);


       viewHolder.itemImage.setImageBitmap(
                decodeSampledBitmapFromResource(getResources(), R.id.item_image, 200, 200));
    }
How to&Answers:
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    Resources res = viewHolder.itemView.getContext().getResources();
    ...
}

Answer:

i can’t use getResources inside onBindViewHolder()?

yes, you can. Use

   viewHolder.itemView.getResources();

getResources() is part View. No need to pass Context around

Answer:

pass the Activity Context this in your Adapter class:

 Context context ;
 public YourAdapter(Context context ,... )  //constructor
 {
    this.context = context ;
    //other code
 }

then u can use:

context.getResources() ;

Answer:

get Context object by the Adapter constructor.

private Context context;

public YourAdapter(Context context){    //or you can make other method  to get/set Context obect
     this.context = context;
}

Then you can use this.context.getResources() to access getResources() method.

And initialize your adapter from Activity or Fragment, like –

YourAdapter yourAdapter = new YourAdapter(getApplicationContext());