BaseAdapter 导致 ListView 在滚动时出现乱序 [英] BaseAdapter causing ListView to go out of order when scrolled

查看:53
本文介绍了BaseAdapter 导致 ListView 在滚动时出现乱序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从书中改编的一些 BaseAdapter 代码有问题.我一直在我的应用程序中到处使用此代码的变体,但只是在滚动长列表时才意识到 ListView 中的项目变得混乱,并且并未显示所有元素.

I'm having problems with some BaseAdapter code that I adapted from a book. I've been using variations of this code all over the place in my application, but only just realized when scrolling a long list the items in the ListView become jumbled and not all of the elements are displayed.

很难描述确切的行为,但如果您将 50 个项目的排序列表向上和向下滚动,则很容易看出.

It's very hard to describe the exact behavior, but it's easy to see if you take a sorted list of 50 items and start scrolling up and down.

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 小部件时将数据放入其中.你需要移动这四行:

You are only putting data in the TextView widgets when they are first created. You need to move these four lines:

        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 小部件,无论你是回收行或创造一个新的.

to be after the if/else block and before the method return, so you update the TextView widgets whether you are recycling the row or creating a fresh one.

这篇关于BaseAdapter 导致 ListView 在滚动时出现乱序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆