【问题标题】:When marking an item (changing background color) in ListView it's repeating for other items在 ListView 中标记项目(更改背景颜色)时,它会重复其他项目
【发布时间】:2023-03-15 08:56:01
【问题描述】:

如果我想标记第二个项目,我正在执行以下代码: 此代码来自我的扩展 ArrayAdapter 的适配器:

if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.channel_list, null);
    } 

    MyContent o = items.get(position);
    if (o != null) {
        TextView tt = (TextView) convertView.findViewById(R.id.toptext);
        TextView bt = (TextView) convertView.findViewById(R.id.bottomtext);
        if (tt != null) {
            tt.setText(o.Top());                            
        }
        if(bt != null){
            bt.setText(o.Bottom());
        }
        if(position == 2) {
            convertView.setBackgroundColor(R.color.selectem_color);
        }
    }
    return convertView;

它将显示列表视图,但在此项目之后标记每个第 9 项(第 11 项第 13 项,依此类推)。

有人知道是什么原因吗?

【问题讨论】:

    标签: android android-listview


    【解决方案1】:

    您没有重置背景颜色。请记住,行被回收——这就是convertView 的用途。只需添加一个else {} 将颜色设置为当position 不是2 时的任何正常状态,你会没事的。

    【讨论】:

    • 当 convertView 不为空时我想要默认颜色我试过 if(position!=2) { return convertView;没有 return 语句(并插入默认颜色)也没有帮助也没有帮助
    • 你不能只返回 convertView。您每次都必须更改颜色。见:github.com/commonsguy/cw-android/tree/master/FancyLists/…
    【解决方案2】:

    有两种情况可以调用getView 方法。如果 converView 为空,则必须创建一个新视图。如果它不为空,则由于用户滚动而离开屏幕的项目将被回收并返回到您的方法以供重用。

    此对象是之前在列表中显示的对象。您必须检查其状态并将其每个属性设置为您希望它具有的值。您不能表现得像对象是新的那样被标记而不是被标记的对象回来。在您的 getview 方法中执行类似的操作。

    if(item is selected) {    
        convertView.setBackgroundColor(selected color);
    } else {
        convertView.setBackgroundColor(not selected color);
    }
    

    在您的代码中缺少 if 的 else 情况。

    【讨论】:

    • 您好,您的回答是对的,但并不能解决问题。回收的元素现在得到了不同的位置,但这是方向。谢谢你的回答!
    • 对不起,阿迪,但我无法知道您的代码是如何工作的。将其更改为更像代码的伪代码。重要的是你不能相信 convertView 是一个干净的新对象,它也可能是一个之前被适配器更改过的对象。
    • 适用于带有“convertView.setBackgroundResource”的图像.. 但不适用于颜色我认为它可能与绘图缓存有关
    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多