<strong>今天和一群初入茅庐的开发者聊天,以为发了如下代码,说只显示一条数据。</strong>
</pre><pre name="code" class="java">public View getView(int position, View convertView, ViewGroup parent) {
helper help = null;
if (convertView == null) {
help = new helper();
convertView = LayoutInflater.from(con).inflate(
R.layout.layout_style, null);
help.name = (TextView) convertView.findViewById(R.id.style_name);
help.score = (TextView) convertView.findViewById(R.id.style_score);
convertView.setTag(help);
}else{
help=(helper) convertView.getTag();
help.name.setText(list.get(position).getName());
help.score.setText(list.get(position).getScore());
System.out.println("convertview:"+position);
}
return convertView;
}原因是getview每执行一次help帮助类都赋空所致。
这样帮助类就有数据了。低级错误往往让人绞尽脑汁。
<pre name="code" class="java">public View getView(int position, View convertView, ViewGroup parent) {
helper help = null;
if (convertView == null) {
help = new helper();
convertView = LayoutInflater.from(con).inflate(
R.layout.layout_style, null);
help.name = (TextView) convertView.findViewById(R.id.style_name);
help.score = (TextView) convertView.findViewById(R.id.style_score);
convertView.setTag(help);
}else{
help=(helper) convertView.getTag();
}
help.name.setText(list.get(position).getName());
help.score.setText(list.get(position).getScore());
return convertView;
}
本文讨论了一个关于ListView在展示多条数据时仅显示一条记录的问题,并给出了修正后的代码实现。问题在于getView方法中每次都会重新为ViewHolder类型的help变量赋值,导致数据覆盖。通过将数据设置的操作移出if-else判断块,确保了ViewHolder的数据正确更新。
421

被折叠的 条评论
为什么被折叠?



