我正在listview适配器类中扩展BaseAdapter类。在这个类中,我在每一行中动态添加图像。但出于某种原因,我在一行中得到了重复的图像数量。
我尝试在getView中动态添加图像时进行日志记录,看起来getView被调用了两次。我该如何解决这个问题?
这是片段:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if(convertView == null){
vi = inflater.inflate(R.layout.myrowlayout, null);
}
HorizontalScrollView horizontalScrollView = (HorizontalScrollView)vi.findViewById(R.id.horizontallayout);
LinearLayout imagesLayout = (LinearLayout)vi.findViewById(R.id.linearlayoutinsidehorizontal);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(...);
//...
LinearLayout.LayoutParams ilp = new LinearLayout.LayoutParams(...);
//...
RowData current = new RowData();
current = data.get(position);
if(current.hasImage()){
//...
ArrayList<String> images = current.getImages();
for(int i = 0; i < images.size(); i++){
ImageView currImage = new ImageView(mActivity);
currImage.setLayoutParams(ilp);
imagesLayout.addView(currImage);
imageLoader.DisplayImage(images.get(i), currImage);
//imageLoader is an implementation of [LazyList] see note below
Log.d("PostListAdapter:getView", "image[" + i + "]: " + images.get(i));
}
horizontalScrollView.removeAllViews();
horizontalScrollView.addView(imagesLayout);
}
return vi;
}
来自onCreate的调用Activity:
list = (ListView)findViewById(R.id.listviewfromlayout);
adapter = new MyAdapter(MyActivty.this, arraylistOfData);
list.setAdapter(adapter);
注意:
我使用LazyList加载所有图片。
答案 0 :(得分:1)
在设置适配器时,使用View holder并按照here
中所述设置标签答案 1 :(得分:1)
这是一个摘录,请注意,您还要在每个视图的绘制调用中保存对findViewById的所有调用。
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
CustomHolder dataHolder = null;
if(convertView == null){
vi = inflater.inflate(R.layout.myrowlayout, null);
HorizontalScrollView horizontalScrollView = (HorizontalScrollView)vi.findViewById(R.id.horizontallayout);
LinearLayout imagesLayout = (LinearLayout)vi.findViewById(R.id.linearlayoutinsidehorizontal);
dataHolder = new CustomHolder(horizontalScrollView, imagesLayout);
vi.setTag(dataHolder);
} else {
dataHolder = vi.getTag();
}
//... Do whatever with the views
return vi;
}
// Custom Holder class
private class CustomHolder{
HorizontalScrollView horizontalScrollView;
LinearLayout imagesLayout;
CustomHolder(HorizontalScrollView hsv, LinearLayout imgLayout){
this.horizontalScrollView = hsv;
this.imagesLayout = imgLayout;
}
}