android listview displays false data after scrolling (custom adapter)

后端 未结 3 2123
感动是毒
感动是毒 2021-01-04 22:06

I\'ve got a strange problem that drives me crazy. In my android application I customized my own adapter that extends from ArrayAdapter. The items of the ListView to which I

3条回答
  •  感情败类
    2021-01-04 22:23

    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.

提交回复
热议问题