我正在尝试将多个视图放入listview,但即使我使用getItemViewType()和getViewTypeCount),它也不起作用,错误是:“ArrayIndexOutofBoundsException length = 2; index = 2;
这是我的代码:
public class SearchAdapter extends BaseAdapter {
private static final int TYPE_MOVIE = 1;
private static final int TYPE_ADS = 2;
private Context context;
private List<MovieObject> movies;
private LayoutInflater inflater;
public SearchAdapter(Context context, List<MovieObject> movies) {
this.context = context;
this.movies = movies;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 2;
}
@Override
public int getItemViewType(int position) {
int separator = (movies.size() / 2) + 1;
if (position == separator) {
return TYPE_ADS;
} else {
return TYPE_MOVIE;
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return movies.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return movies.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
View v = convertView;
ViewHolder h = null;
ViewHolderAds h2 = null;
if (v == null) {
h = new ViewHolder();
switch (type) {
case TYPE_MOVIE:
v = inflater.inflate(R.layout.adapter_search, null);
h = new ViewHolder();
break;
case TYPE_ADS:
v = inflater.inflate(R.layout.view_ads, null);
h2 = new ViewHolderAds();
v.setTag(h2);
break;
default:
break;
}
v.setTag(h);
} else {
if (type == TYPE_MOVIE) {
h = (ViewHolder) v.getTag();
} else {
h2 = (ViewHolderAds) v.getTag();
}
}
return v;
}
private class ViewHolder {
TextView tv_title, tv_date, tv_certification, tv_runtime;
}
private class ViewHolderAds {
}
}
答案 0 :(得分:0)
更改
private static final int TYPE_MOVIE = 1;
private static final int TYPE_ADS = 2;
与
private static final int TYPE_MOVIE = 0;
private static final int TYPE_ADS = 1;
内部android使用这些常量作为视图数组的索引,其大小由getViewTypeCount()
返回,并且你不能拥有索引为2的大小为2的数组(这就是异常告诉你的)