android – BaseAdapter导致ListView在滚动时出错

前端之家收集整理的这篇文章主要介绍了android – BaseAdapter导致ListView在滚动时出错前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从一本书改编的一些BaseAdapter代码中遇到问题.我一直在应用程序中使用这些代码的变体,但是只有在滚动长列表时才意识到,ListView中的项目变得混乱,并不是所有的元素都显示出来.

很难描述确切的行为,但是很容易看出你是否选择了50个项目的排序列表,并开始向上和向下滚动.

@H_502_4@class ContactAdapter extends BaseAdapter { ArrayList<Contact> mContacts; public ContactAdapter(ArrayList<Contact> contacts) { mContacts = contacts; } @Override public int getCount() { return mContacts.size(); } @Override public Object getItem(int position) { return mContacts.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position,View convertView,ViewGroup parent) { View view; if(convertView == null){ LayoutInflater li = getLayoutInflater(); view = li.inflate(R.layout.groups_item,null); TextView label = (TextView)view.findViewById(R.id.groups_item_title); label.setText(mContacts.get(position).getName()); label = (TextView)view.findViewById(R.id.groups_item_subtitle); label.setText(mContacts.get(position).getNumber()); } else { view = convertView; } return view; } }

解决方法

当您首次创建TextView小部件时,您只会将数据放入.你需要移动这四行: @H_502_4@TextView label = (TextView)view.findViewById(R.id.groups_item_title); label.setText(mContacts.get(position).getName()); label = (TextView)view.findViewById(R.id.groups_item_subtitle); label.setText(mContacts.get(position).getNumber());

在if / else块之后和方法返回之前,所以您可以更新TextView小部件,无论是回收该行还是创建新的行.

猜你在找的Android相关文章