从几天开始,我正在试图找出为什么我的自定义适配器迭代次数超过应有的数量。我正在尝试显示3个项目,但我的自定义适配器比预期多次进入函数getView()
。
每次输入getView()时都会打印log
,logcat会显示:
log-entered getView log-entered getView log-entered getView log-entered getView log-entered getView log-entered getView . . . so on..
这种情况发生了5次,每次getView()都会发生3次。
主要活动的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_torneos);
final ListView listTorneos=(ListView) findViewById(R.id.listViewTorneos);
ArrayList<Torneo> list = getListData();
listTorneos.setAdapter(new CustomListAdapter(this,list));
}
private ArrayList<Torneo> getListData() {
ArrayList<Torneo> results = new ArrayList<Torneo>();
Torneo torneo = new Torneo();
torneo.setNombre("Timiza");
torneo.setLugar("Parque metropolitano timiza1");
torneo.setCiudad("Bogota");
results.add(torneo);
torneo = new Torneo();
torneo.setNombre("salitre");
torneo.setLugar("Parque metropolitano timiza2");
torneo.setCiudad("Bogota");
results.add(torneo);
torneo = new Torneo();
torneo.setNombre("laverdieri");
torneo.setLugar("Parque metropolitano timiza3");
torneo.setCiudad("Bogota");
results.add(torneo);
return results;
}
我的 CustomAdapter类的代码:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<NewsItem> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<NewsItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("info","log-entered getView");
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewsItem newsItem = (NewsItem) listData.get(position);
holder.headlineView.setText(newsItem.getHeadline());
holder.reporterNameView.setText("By, " + newsItem.getReporterName());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reporterNameView;
TextView reportedDateView;
ImageView imageView;
}
}
答案 0 :(得分:2)
每个布局传递可以多次调用getView(对于每个子节点的onMeasure和onLayout)。您正在回收视图并使用View Holder(避免性能问题的技术),那么问题是什么?