我正在使用GridView适配器显示图像(在R.drawable中)和图像下的文本描述(两者都在数组列表的strings.xml文件中编码)。我想在单击特定图像时在新活动中显示图像和文本。
仔细观察,我发现由于图像大小,最好使用int而不是位图作为图像,但是我遇到了适配器的问题......
该行:“holder.image.setImageResource(imgs.getResourceId(0,-1));”如下所示在logcat中给我一个错误。
有什么建议吗?
GridViewAdapter代码:
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
// problem code >>> holder.image.setImageResource(imgs.getResourceId(0, -1));
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
答案 0 :(得分:0)
你的getView方法应如下所示。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageResource(imgs.getResourceId(0, -1));
return row;
}
您的视图持有者类应如下所示
static class ViewHolder {
public TextView imageTitle;
public ImageView image;
public ViewHolder(View view) {
image = (ImageView) view.findViewById(R.id.image);
imageTitle = (TextView) view.findViewById(R.id.text);
}
}