我的 ListView 有两种不同类型的布局:一种有图像,另一种没有图像。我尝试做类似 this 的事情.我覆盖了 BaseAdapter 的 getView:
public View getView(int position, View convertView, ViewGroup parent) {
Map<String, String> item = mData.get(position);
if(item.get("image_location").equals("") == true){
ViewHolderWithoutImage holder = new ViewHolderWithoutImage();
if(convertView == null){
convertView = mInflater.inflate(R.layout.row_without_image, null);
holder.title = (TextView)convertView.findViewById(R.id.title);
holder.firstParagraph = (TextView)convertView.findViewById(R.id.first_paragraph);
convertView.setTag(holder);
}else{
holder = (ViewHolderWithoutImage)convertView.getTag();
}
holder.title.setText(mData.get(position).get("title").toString());
holder.firstParagraph.setText(item.get("first_paragraph").toString());
}else{
ViewHolderWithImage holder = new ViewHolderWithImage();
Bitmap bm = null;
if(convertView == null){
convertView = mInflater.inflate(R.layout.row_with_image, null);
holder.title = (TextView)convertView.findViewById(R.id.title_image);
holder.firstParagraph = (TextView)convertView.findViewById(R.id.first_paragraph_image);
holder.image = (ImageView)convertView.findViewById(R.id.image);
convertView.setTag(holder);
}else{
holder = (ViewHolderWithImage)convertView.getTag();
}
holder.title.setText(mData.get(position).get("title").toString());
holder.firstParagraph.setText(item.get("first_paragraph").toString());
String location = imageBaseUrl + item.get("image_location");
bm = downloadImage(location);
holder.image.setImageBitmap(bm);
}
return convertView;
}
我的 ViewHolders 类:
static class ViewHolderWithImage {
TextView title;
TextView firstParagraph;
ImageView image;
}
static class ViewHolderWithoutImage {
TextView title;
TextView firstParagraph;
}
它在没有第二部分的情况下也能工作,但是当它进入时会崩溃
holder = (ViewHolderWithImage)convertView.getTag();
部分当 item.get("image_location").equals("") != true
出现 java.lang.reflect.InvocationTargetException
时。有什么办法可以解决这个问题吗?
最佳答案
我认为这是因为 convertView 的标签持有不同类型的 ViewHolder。尝试检查 convertView
类型:
if(item.get("image_location").equals("") == true){
...
if(convertView == null || !(convertView.getTag() instanceof ViewHolderWithoutImage)){
...
}else{
...
if(convertView == null || !(convertView.getTag() instanceof ViewHolderWithImage)){
convertView = mInflater.inflate(R.layout.row_with_image, null);
...
附言最好使用系统方法来处理不同的布局(覆盖 getItemViewType()
)。 There is good article on this topic .
关于android - 具有不同项目布局的 ListView 的 ViewHolders,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5634781/