adapter中怎么获取resid
时间: 2024-03-20 17:43:08 浏览: 21
在Android中,我们通常可以通过Context获取到资源文件的id。在Adapter中,我们可以通过构造方法传入一个Context对象,然后通过该Context对象的getResources()方法获取到Resources对象,进而获取到对应的资源文件id。
例如,在一个RecyclerView的Adapter中,可以在构造方法中传入一个Context对象,并在ViewHolder中使用该Context对象获取到对应的资源文件id,例如:
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context mContext;
private List<String> mData;
public MyAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text_view);
}
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_item_layout, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String text = mData.get(position);
holder.mTextView.setText(text);
// 获取到资源文件id
int resId = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
// 使用resId来设置ImageView的图片
holder.mImageView.setImageResource(resId);
}
@Override
public int getItemCount() {
return mData.size();
}
}
```
在上面的代码中,我们在ViewHolder中获取到了一个ImageView的资源文件id,然后使用该id来设置ImageView的图片。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)