Listview Adapter的getView方法
@Override
public Object getItem(int position) {
return mlist.get(position);
}
// 最好也重写该方法 布局类型的数量
@Override
public int getViewTypeCount() {
return 4;
}
// 重写该方法即可避免ClassCastExcepiton 返回该布局类型必须从0开始
@Override
public int getItemViewType(int position) {
int type = mlist.get(position).getType();
return type;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
DataBean dataBean = (DataBean) getItem(position);
int type = getItemViewType(position);
ViewHolder1 holder1 = null;
ViewHolder2 holder2 = null;
ViewHolder3 holder3 = null;
ViewHolder4 holder4 = null;
if (convertView == null) {
inflater = LayoutInflater.from(mContext);
// 按当前所需的样式,确定new的布局
switch (type) {
case TYPE_1:
convertView = inflater.inflate(R.layout.lv_information_item,
parent, false);
holder1 = new ViewHolder1(convertView);
convertView.setTag(holder1);
break;
case TYPE_2:
convertView = inflater.inflate(R.layout.lv_information_video_item,
parent, false);
holder2 = new ViewHolder2(convertView);
convertView.setTag(holder2);
break;
case TYPE_3:
convertView = inflater.inflate(R.layout.lv_information_activite_item,
parent, false);
holder3 = new ViewHolder3(convertView);
convertView.setTag(holder3);
break;
case TYPE_4:
convertView = inflater.inflate(R.layout.lv_information_live_video_item,
parent, false);
holder4 = new ViewHolder4(convertView);
convertView.setTag(holder4);
break;
default:
break;
}
} else {
switch (type) {
case TYPE_1:
holder1 = (ViewHolder1) convertView.getTag();
break;
case TYPE_2:
holder2 = (ViewHolder2) convertView.getTag();
break;
case TYPE_3:
holder3 = (ViewHolder3) convertView.getTag();
break;
case TYPE_4:
holder4 = (ViewHolder4) convertView.getTag();
break;
}
}
switch (type) {
case TYPE_1:
showHolder1(holder1, dataBean);
break;
case TYPE_2:
showHolder2(holder2, dataBean);
break;
case TYPE_3:
showHolder3(holder3, dataBean);
break;
case TYPE_4:
showHolder4(holder4, dataBean);
break;
}
return convertView;
}
void showHolder1(ViewHolder1 viewHolder, final DataBean dataBean) {
// 将数据显示到控件上
}
void showHolder2(ViewHolder2 viewHolder, final DataBean dataBean) {
// 将数据显示到控件上
}
void showHolder3(ViewHolder3 viewHolder, final DataBean dataBean) {
// 将数据显示到控件上
}
void showHolder4(ViewHolder4 viewHolder, final DataBean dataBean) {
// 将数据显示到控件上
}
public class ViewHolder1 {
// 控件初始化
@Bind(R.id.type1)
TextView type1;
ViewHolder1(View view) {
ButterKnife.bind(this, view);
}
}
public class ViewHolder2 {
// 控件初始化
@Bind(R.id.type2)
TextView type2;
ViewHolder2(View view) {
ButterKnife.bind(this, view);
}
}
public class ViewHolder3 {
// 控件初始化
@Bind(R.id.type3)
TextView type3;
ViewHolder3(View view) {
ButterKnife.bind(this, view);
}
}
public class ViewHolder4 {
// 控件初始化
@Bind(R.id.type4)
TextView type4;
ViewHolder4(View view) {
ButterKnife.bind(this, view);
}
}
}
这样就实现了多布局以及复用,但是如果不重写getItemViewType方法会发生ClassCastException的错误