java - 如何为 GrideView 列表添加 ViewHolder?
问题描述
我正在尝试ViewHolder
为此GridView
列表编写一个,但每次都会出错。你能告诉我如何为这个 gridView 列表制作一个正确的 ViewHolder 吗?
我的代码:
public static String[] stringArray = {"IRAN","Uganda",
"Ukraine","United Arab Emirates","United Kingdom","United States Minor Outlying Islands",};
public int[] imageArray = {R.drawable.iran,R.drawable.united_states,R.drawable.iran,R.drawable.russia,
R.drawable.iran,R.drawable.united_states,R.drawable.iran,R.drawable.uk,
R.drawable.iran,R.drawable.united_states };
public CountryImageAdapter(Context mContext) {this.mContext = mContext;}
@Override
public int getCount() {return imageArray.length;}
@Override
public Object getItem(int position) {return imageArray[position];}
@Override
public long getItemId(int position) {return 0;}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {View v;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.sample_gridlayout, null);
v.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TextView textView = (TextView) v.findViewById(R.id.country_text);
ImageView imageView = (ImageView) v.findViewById(R.id.ivGallery);
textView.setText(stringArray[position]);
imageView.setImageResource(imageArray[position]);
return v;}
解决方案
你应该创建一个扩展 RecyclerView.ViewHolder 的 customViewHolder 类,你应该在那里找到你的视图:
TextView textView = (TextView) v.findViewById(R.id.country_text);
ImageView imageView = (ImageView) v.findViewById(R.id.ivGallery);
你应该把这些行:
textView.setText(stringArray[position]);
imageView.setImageResource(imageArray[position]);
在 onBindViewHolder 函数中。
推荐阅读
- python - 从列中删除值时 Pandas keyerror
- vue.js - 删除后自动重新加载列表项(Vue.js)
- css - 在弹出窗口中显示大部分未显示的元素
- javascript - 如何从 Microsoft.Toolkit.Wpf.UI.Controls.WebView 中的不同域访问 iframe DOM?
- node.js - Typescript + Express:类型“typeof e”没有兼容的调用签名
- jquery - 在 $.ajax() 中传递表单数据、输入文本数据和下拉数据
- python - 运行基于 selenium 的 exe 来抓取数据
- ruby-on-rails - Ruby on Rails:将 JSON 显示从一个控制器渲染到另一个控制器
- android - android camera2 发布资源无法正常工作
- android - 针对不同应用程序/多租户架构的一种数据库和 REST 服务