首页 > 解决方案 > 如何为 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;}

标签: javaandroidandroid-viewholder

解决方案


你应该创建一个扩展 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 函数中。


推荐阅读