android listview displays false data after scrolling (custom adapter)

后端 未结 3 2112
感动是毒
感动是毒 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:25

    As everyone says, Android recycle the views. What does that mean? Imagine you have 10 items in your list, but only 3 of them are displayed on the screen. When scrolling down, the first will disappear and the forth will appear. The fourth item was already in the Android system, but the fifth was created from the first item, using the same view. In my case, I had a TextView with a default background. But if some condition was met, I change the background.

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
        if (someCondition) {
            holder.textView.setBackground(R.drawable.different_background)
        }
        ...
    }
    

    The problem was that I don't set back the default background if the condition is not met (as I thought that the view was created for each item). The problem appeared when the first item had the condition true, so the recycled view was used with the different_background instead of the default background. To avoid the problem, I had to always set both branches of the condition and set the default values as follows:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
        if (someCondition) {
            holder.textView.setBackground(R.drawable.different_background)
        } else {
            holder.textView.setBackground(R.drawable.default_background)
        }
        ...
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题