BaseAdapter在getView()方法调用上返回错误的位置

时间:2014-12-05 00:08:06

标签: android listview android-listview android-adapter

奇怪的是,我的CustomBaseAdapter正在为需要膨胀的项目返回错误的位置,因此适配器会在行上显示错误的数据类型!

虽然我正在使用ViewHolder模式,但我的ListView layout_height设置为match_parent,并且我已找到的每种可能的方式,以确保ListView项目的稳定性,已经实现,{ {1}}似乎没有回应。

getView()方法

CustomBaseAdapter

其他方法

@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        mItemView = convertView;
        if (convertView == null) {
            mItemView = mInflater.inflate(R.layout.layout_listview_row, parent, false);
            holder = new ViewHolder();
            //setting up the Views
            mItemView.setTag(holder);
        } else {
            holder = (ViewHolder) mItemView.getTag();
        }

        //Getting the item
        final MyItem item = getItem(position);

        //Doing some checks on my item and then display the appropriate data.

        //By saying checks i mean something like: 

        if(item.getSomething().equals("blabla")){
           //Load some pic
        }else{
           //Load another pic
        }
        //Now when i have scrolled the list once and return back to top,
        //Suddenly in Logcat i am seeing that the first row is getting matched to
        //the object in the 4th position, but it doesnt display its data. It displays
        //the text from the first item as it was supposed to do. But the relation between
        //the first row and the item's position is like 0->4. 
}

我在Google上搜索并尝试了所有内容!似乎什么都没有给我一个解决方案。

任何帮助将不胜感激!如果您需要更多代码,请告诉我。

2 个答案:

答案 0 :(得分:2)

您正在“回收”显示对象,但您有责任将正确的数据输入其中。问题是这行代码:

    mItemView = convertView;

convertView是您数据的“容器”。如果convertView不为null,则构造容器,但您必须将适当的数据放入其中。这通常通过“使用”位置指示器来完成。

也许是这样的:

    if (convertView == null) {
        mItemView = mInflater.inflate(R.layout.layout_listview_row, parent, false);
        holder = new ViewHolder();
        //setting up the Views
        mItemView.setTag(holder);
    } else {
        holder = getItem(position);
        mItemView.setTag(holder);
    }

答案 1 :(得分:1)

我怀疑mItemView是罪魁祸首。根据名称判断,这是一个实例字段,因此如果getView()中有多个线程调用CustomBaseAdapter,那么mItemView可能会更改它指向您的鼻子下方的哪个回收视图。另外,我假设getView()return mItemView结尾,对吧?

无论如何,我建议尝试删除mItemView并写下这样的函数:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.layout_listview_row, parent, false);
        ViewHolder holder = new ViewHolder();
        //setting up the Views
        convertView.setTag(holder);
    }

    ViewHolder holder = (ViewHolder) convertView.getTag();

    // ...

    return convertView;
}