在自定义adapter中需要重写两个方法:getItemViewType() 、 getViewTypeCount(), getViewTypeCount这个方法返回是布局的数量,当返回的布局大于1时,adapter 会分配多个convertview,而根据getItemViewType 返回的type进行标记, getItemViewType返回的type是从0-n 开始的,也就是和数组的下标相同,如果返回的type >=getViewTypeCount 就会报错。以下代码是业务逻辑的一部分。仅供参考。
public class MessageFlowAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
private List<MessageFlowModel> messageList;
private Context context;
private DisplayImageOptions options;
private final static float imgWidth = 400f;
private int width;
private final static int TYPE_1 = 0;
private final static int TYPE_2 = 1;
private final static int TYPE_3 = 2;
private final static int TYPE_4 = 3;
private int textViewWidth = 0;
private int alphaCardId[] = {R.drawable.messagebox_car1, R.drawable.messagebox_car2, R.drawable.messagebox_car3, R.drawable.messagebox_car4};
private long currentTime;
private int timePosition;
private boolean timeSetFlag = false;
public MessageFlowAdapter(Activity context, List<MessageFlowModel> messageList, DisplayImageOptions options, long currentTime, int timePosition) {
this.messageList = messageList;
this.context = context;
this.options = options;
Display display = context.getWindowManager().getDefaultDisplay();
System.out.println(" width Message screen : " + display.getWidth());
width = (display.getWidth() * 4 / 6) - 50;
mInflater = LayoutInflater.from(context);
this.currentTime = currentTime;
this.timePosition = timePosition;
}
public boolean isTimeSetFlag() {
return timeSetFlag;
}
public void setTimeSetFlag(boolean timeSetFlag) {
this.timeSetFlag = timeSetFlag;
}
public int getTimePosition() {
return timePosition;
}
public void setTimePosition(int timePosition) {
this.timePosition = timePosition;
}
public void setData(List<MessageFlowModel> messageList) {
this.messageList = messageList;
}
public final class ViewHolderConsultantNoCar {
public TextView consultantWords;
public TextView timeLong;
}
public final class ViewHolderConsultantWords {
public TextView consultantWords;
public TextView timeLong;
}
public final class ViewHolderCustomWords {
public TextView customWords;
public TextView timeLong;
}
public final class ViewHolderRecommendCar {
public TextView recommendWords;
public ImageView alphaImage;
public ImageView carImage;
public RelativeLayout recommendCarRelative;
public TextView timeLong;
public TextView timeShort;
public TextView carNum;
public ImageView carShadow;
public TextView timeCount;
}
@Override
public int getCount() {
return messageList.size();
}