在ListView中标记项目(更改背景颜色)时,它会重复其他项目

时间:2010-05-30 18:18:14

标签: android android-listview

如果我想标记第二项,我正在执行以下代码: 此代码来自我的适配器,它扩展了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项,依此类推)。

有谁知道是什么原因?

2 个答案:

答案 0 :(得分:3)

您没有重置背景颜色。请记住,行被回收 - 这就是convertView的用途。只需添加else {}即可将颜色设置为position不是2时的正常状态,您就可以了。

答案 1 :(得分:2)

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

此对象是之前列表中显示的对象。您必须检查其状态并将其的每个属性设置为您希望它具有的值。您不能表现得像是新标记的对象,而不是标记对象。在你的getview方法中做这样的事情。

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

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