作者:三喜金融 | 来源:互联网 | 2023-06-12 18:15
ListView多布局展示用处很多
该异常如下:
这是怎么回事呢?
具体代码如下:
public static final int TYPE_MALE = 1;
public static final int TYPE_FEMALE = 2;
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
String sex = list.get(position).getSex();
switch (sex) {
case "男":
return TYPE_MALE;
case "女":
return TYPE_FEMALE;
default:
return TYPE_MALE;
}
}
TYPE_MALE = 1和TYPE_FEMALE = 2,这两个值不可以随意赋值,必须从0开始,一次增大
对代码做修正其他地方,无需修改就可以正常运行了
public static final int TYPE_MALE = 0;
public static final int TYPE_FEMALE = 1;
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
String sex = list.get(position).getSex();
switch (sex) {
case "男":
return TYPE_MALE;
case "女":
return TYPE_FEMALE;
default:
return TYPE_MALE;
}
}
listView的多布局展示中getView方法最重要,再次贴出该段代码
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View ret = null
ViewHolder1 holder1 = null
ViewHolder2 holder2 = null
int type = getItemViewType(position)
//进行复用,如果convertView为空,根据type生成对应布局
if (convertView != null) {
ret = convertView
} else {
switch (type) {
case TYPE_MALE:
ret = LayoutInflater.from(context).inflate(R.layout.item_man, null)
break
case TYPE_FEMALE:
ret = LayoutInflater.from(context).inflate(R.layout.item_femal, null)
break
}
}
//实例化ViewHolder ,findViewById
switch (type) {
case TYPE_MALE:
holder1 = (ViewHolder1) ret.getTag()
if (holder1 == null) {
holder1 = new ViewHolder1()
holder1.man_image = ((ImageView) ret.findViewById(R.id.man_image))
holder1.man_name = ((TextView) ret.findViewById(R.id.man_name))
holder1.sex = ((TextView) ret.findViewById(R.id.sex))
ret.setTag(holder1)
}
break
case TYPE_FEMALE:
holder2 = (ViewHolder2) ret.getTag()
if (holder2 == null) {
holder2 = new ViewHolder2()
holder2.female_image_One= ((ImageView) ret.findViewById(R.id.femal_image_one))
holder2.female_image_two = ((ImageView) ret.findViewById(R.id.femal_image_two))
holder2.female_name = ((TextView) ret.findViewById(R.id.femal_name))
holder2.sex = ((TextView) ret.findViewById(R.id.sex))
ret.setTag(holder2)
}
break
}
//进行赋值
switch (type) {
case TYPE_MALE:
holder1.man_image.setImageResource(list.get(position).getImage())
holder1.man_name.setText(list.get(position).getName())
holder1.sex.setText(list.get(position).getSex())
break
case TYPE_FEMALE:
holder2.female_image_one.setImageResource(list.get(position).getImage())
holder2.female_image_two.setImageResource(list.get(position).getImage())
holder2.female_name.setText(list.get(position).getName())
holder2.sex.setText(list.get(position).getSex())
break
}
return ret
}