开发者

When marking an item (changing background color) in ListView it's repeating for other items

If I want to mark the second item I'm doing the following code: This code is from my Adapter that extends 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;

It will show the list view but mark every 9'th item after this item (the 11'th item 13'th and so on).

Does anyone know what's the reason?


You are not resetting the background color. Remember that rows are recycled -- that is what the convertView is for. Just add an else {} to set the color to whatever your normal state is when position is not 2, and you'll be fine.


There are two cases in which the getView method can be called. If converView is null you have to create a new View. If it is not null an item that left the screen because of the user scrolling is recycled and returned to your method to be reused.

This object is an object that was shown in the list before. You have to check its state and set every property of it to the value you want it to have. You can't act like the object is new you get marked and not marked objects back. Do something like this in your getview method.

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

In your code the else case of the if is missing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜