我有两个listview布局。(一个用于分隔符,另一个用于列表项) 我为每个布局都有两个视图持有者类。如何在listview中正确使用这些不同的布局?
以下是我的getView()
自定义适配器方法。
@Override
public View getView(int position, View convertView, ViewGroup parent){
int pos = position;
final Context context = parent.getContext();
int viewType = this.getItemViewType(position);
View view = convertView;
switch(viewType){
case TYPE_ITEM:
HolderItem holder_item;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, parent, false);
holder_item = new HolderItem();
holder_item.title = (TextView) view.findViewById(R.id.title);
holder_item.subTitle = (TextView) view.findViewById(R.id.sub_title);
view.setTag(holder_item);
}else{
holder_item = (HolderItem) view.getTag();
}
holder_item.title.setText(titleList.get(pos));
holder_item.subTitle.setText(infoList.get(pos));
return view;
case TYPE_SEPARATOR:
HolderSeparator holder_sep;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
holder_sep = new HolderSeparator();
holder_sep.separator = (TextView) view.findViewById(R.id.list_header);
view.setTag(holder_sep);
}else{
holder_sep = (HolderSeparator)view.getTag();
}
holder_sep.separator.setText(titleList.get(pos));
return view;
default:
return view;
}
}
public int getItemViewType(int position){
if(position == 0 || position == 5) return TYPE_SEPARATOR;
else return TYPE_ITEM;
}
class HolderItem{
TextView title;
TextView subTitle;
}
class HolderSeparator{
TextView separator;
}
有两个分隔符(在listview的顶部和listview的中间)
上面的代码工作正常,但是当我开始滚动时,它出现ClassCastException
java.lang.ClassCastException: com.soonoo.listtest.Adapter$Holder cannot be cast to com.soonoo.listtest.Adapter$HolderItem
我认为我的代码使用了两个视图持有者,当滚动时,新的列表项使用分隔符的视图持有者。我该如何解决?
答案 0 :(得分:0)
如果您覆盖getItemViewType()
,则还需要覆盖getViewTypeCount()
,以指明您有多少种不同的行类型。