问题:在对listview进行操作时,发现选中第1行,页面往下滚,第12行,第23行,第34行……都默认选中了。。。(布局上,测试发现后面数据并没有真的选中……)
原因:
<span style="font-family:simsun;"> @Override
public View getView(int position, View convertView, ViewGroup parent) {
final ContactItem contactItem = getItem(position); // 获取当前项的ContactItem实例
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.txt_name = (TextView) view.findViewById(R.id.txt_name);
viewHolder.txt_phone = (TextView) view.findViewById(R.id.txt_phone);
viewHolder.btn_check = (CheckBox) view.findViewById(R.id.btn_check);
view.setTag(viewHolder); // 将viewHolder存储到view中
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag(); // 重新获取viewHolder
}
}</span>
View convertView只在第一页显示的那些item是被创建的,当你滚动到下一页的时候,就会重复使用,这时候就会出问题。
解决:
/**
* 定义了一个HashMap<Integer,View> lmap,
* 在getView()方法中,使用lmap.put(position, view)把每个view和position一一对应起来,
* 对于已经建立的view,使用view = lmap.get(position)来取,这样既可以保存改变的状态,又不会重复。
*/
<span style="color:#ff0000;">HashMap<Integer,View> lmap = new HashMap<Integer,View>();</span>
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ContactItem contactItem = getItem(position); // 获取当前项的ContactItem实例
View view;
ViewHolder viewHolder;
if (<span style="color:#ff0000;">lmap.get(position) == null</span>) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.txt_name = (TextView) view.findViewById(R.id.txt_name);
viewHolder.txt_phone = (TextView) view.findViewById(R.id.txt_phone);
viewHolder.btn_check = (CheckBox) view.findViewById(R.id.btn_check);
<span style="color:#ff0000;">lmap.put(position, view);</span>
view.setTag(viewHolder); // 将viewHolder存储到view中
} else {
<span style="color:#ff0000;">view = lmap.get(position);</span>
viewHolder = (ViewHolder) view.getTag(); // 重新获取viewHolder
}
}
参考文章: http://blog.sina.com.cn/s/blog_713953c5010123k6.html