我正在尝试为此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函数中。