views:

155

answers:

2

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?

+3  A: 

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.

CommonsWare
+1 for a working solution :D
Roflcoptr
trying it now thanks :)
Adi
I want the default colorwhen convertView isn't null i tried if(position!=2) { return convertView; }didn't helpalso without the return statement (and inserting the default color) didn't help
Adi
You cannot just return convertView. You *have to change the color, every time*. See: http://github.com/commonsguy/cw-android/tree/master/FancyLists/Recycling/
CommonsWare
+1  A: 

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.

Janusz
Hi your answer is right but it doesn't solve it. the recycled element gets a different position now, but this is the direction.Thanks for you answer!
Adi
Sorry Adi but I can't possible know how your code works. Changed it a to a more pseudo code like code. The important thing is that you can't trust the convertView to be a clean new Object it also could be an object that was changed by the adapter before.
Janusz
Works for images with "convertView.setBackgroundResource".. but not for colorsI think it might be related for the drawing cache
Adi