BaseAdapter导致ListView在滚动时出现故障

Aus*_*ner 9 android listview

我遇到了一些我从一本书改编的BaseAdapter代码的问题.我一直在我的应用程序中使用此代码的变体,但只是在滚动一个长列表时才实现ListView中的项目变得混乱而不是所有元素都显示出来.

描述确切的行为非常困难,但很容易看出你是否采用了50个项目的排序列表并开始上下滚动.

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 13

您只是在TextView首次创建小部件时将数据放入其中.你需要移动这四行:

        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());
Run Code Online (Sandbox Code Playgroud)

if/ elseblock之后和方法返回之前,因此您更新TextView小部件,无论是回收行还是创建新行.


wiz*_*ail 5

为了进一步澄清CommonsWare的答案,这里有一些更多的信息:

li.inflate操作(这里需要从XML行的布局解析和创建适当的视图对象)由包裹如果(convertView == NULL)效率语句,因此同一对象的通货膨胀不会发生每当它进入视图时一次又一次.

但是,getView方法的其他部分用于设置其他参数,因此不应包含在if(convertView == null){} ... else {}语句中.

在许多常见的实现该方法的,一些TextView的标签,或ImageView的元素的ImageButton需要由值从列表[位置]填充,使用findViewById和后.setText.setImageBitmap操作.这些操作必须来后被通货膨胀从头开始创建一个视图,并让现有视图如果不为null(例如,在刷新).

将此解决方案应用于ListView ArrayAdapter的另一个好例子出现在/sf/answers/271224761/