我想在ListView中使用ViewHolder模式(我知道RecyclerView,但我想在ListView中使用它)。
我创建了它,但我注意到getView()中的convertView始终为null。每次调用getView()。我做错了什么?
public class ScheduleListAdapter extends BaseAdapter {
private LayoutInflater lInflater;
private List<ScheduleSubject> scheduleListItems;
public ScheduleListAdapter(Context context, List<ScheduleSubject> scheduleListItems) {
this.scheduleListItems = scheduleListItems;
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return scheduleListItems.size();
}
@Override
public Object getItem(int position) {
return scheduleListItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
TextView name, place;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = lInflater.inflate(R.layout.schedule_item_show, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.schedule_item_name_textView);
viewHolder.place = (TextView) convertView.findViewById(R.id.schedule_item_place_textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ScheduleSubject scheduleListItem = getScheduleListItem(position);
viewHolder.number.setText(String.valueOf(scheduleListItem.getLessonNumber()));
viewHolder.name.setText(scheduleListItem.getName());
viewHolder.place.setText(scheduleListItem.getPlace());
return convertView;
}
public ScheduleSubject getScheduleListItem(int position) {
return ((ScheduleSubject) getItem(position));
}
}
答案 0 :(得分:0)
尝试替换此行
ViewHolder viewHolder;
这一个:
Holder viewHolder;
和这一个:
viewHolder = (ViewHolder) convertView.getTag();
这一个:
viewHolder = (Holder) convertView.getTag();