简体   繁体   English

如何在onBindViewHolder()中使用getResources?

[英]How can I use getResources inside of onBindViewHolder()?

I have this method, and I want to use getResources() inside it: 我有这个方法,我想在里面使用getResources():

 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));
    }
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    Resources res = viewHolder.itemView.getContext().getResources();
    ...
}

i can't use getResources inside onBindViewHolder()? 我不能在onBindViewHolder()中使用getResources?

yes, you can. 是的你可以。 Use 采用

   viewHolder.itemView.getResources();

getResources() is part View . getResources()View的一部分。 No need to pass Context around 无需传递Context

pass the Activity Context this in your Adapter class: 通过Activity语境this在你的适配器类:

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

then u can use: 然后你可以使用:

context.getResources() ;

get Context object by the Adapter constructor. 通过Adapter构造函数获取Context对象。

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. 然后,您可以使用this.context.getResources()来访问getResources()方法。

And initialize your adapter from Activity or Fragment, like - 并从Activity或Fragment初始化你的适配器,如 -

YourAdapter yourAdapter = new YourAdapter(getApplicationContext());

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

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