android listview displays false data after scrolling (custom adapter)

只愿长相守 提交于 2019-11-30 19:53:45

I had a similar problem with multiple item types in the list. In my case the list item was either a section (label) item or a common list item.

To work with such types of lists, you should override getViewTypeCount and getItemViewType methods. Something like this:

private static final int ITEM_VIEW_TYPE_ITEM = 0;
private static final int ITEM_VIEW_TYPE_SEPARATOR = 1;

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public int getItemViewType(int position) {
    return this.getItem(position).isSection() ? ITEM_VIEW_TYPE_SEPARATOR : ITEM_VIEW_TYPE_ITEM;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final Item item = this.getItem(position);

    if (convertView == null) {
        convertView = mInflater.inflate(item.isSection() ? R.view1 : R.view2, null);
    }

    if(item.isSection()){
        //...
    }
    else{
        //...
    }

    return convertView;
}

Then the convertView parameter will always be correct and contain that type which you need.

And another thing: you explicitly added the public Param[] params field when you already have it in the base class ArrayAdapter<Param>.

I would recommend to inherit from the BaseAdapter class.

Edit: Here is the code which you can try to use in order to make your Spinner work:

sp.setTag(p);
sp.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View convertView, int pos, long id) {
    Param currentItem = (Param)parent.getTag();
    currentItem.setDefData(currentItem.getData().get(pos));
    currentItem.setChanged(true);
}
//...

Try to use the combination of the getTag and setTag methods. I remember that I had similar problems with event handlers and final variables, but I completely forgot the cause of them, so I can't explain exactly why this happens.

As mentioned by Sam, Android system always tries to recycle if possible to conserve resources. That means, developers need to keep track of the View on ListView themselves. For the entity, or so-called the presentation data structure, you can have something to keep track of the selected/de-selected state, for example:

class PresentationData {
    // other stuffs..
    boolean isSelected = false;
}

Mapping these data structures to the Adapter, and if any item clicked, set the state to true: listPresentationData.get(selected_position).isSelected = true

Ok so in the getView() of the adapter, keep track the presentation correctly for your data.

if(listPresentationData.get(position).isSelected) 
{ 
    // set background color of the row layout..or something else 
}

Also, worth to mention is better to have a memory cache for every views, usually called ViewHolder to improve performance as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!