0
votes

Good evening StackOverflow

This time I'm fighting with a ListView Containing TextViews.

I add an OnItemClick Listener.

    v.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            TextView tvItm = (TextView) arg1;
            int Col = tvItm.getTextColors().getDefaultColor();
            if (Col == Color.WHITE)
                tvItm.setTextColor(Color.GREEN);
            else
                tvItm.setTextColor(Color.WHITE);
        }
    });

As you can see I toggle the color of the text, and it works.. BUT, it works on several items at a time, even though i only click one item. So when I click the first item, it turns green, then there's six white items, and the 7th item is green, but i never clicked the 7th item!!

item1 - clicked - green
item2 - not clicked - white
item3 - not clicked - white
item4 - not clicked - white
item5 - not clicked - white
item6 - not clicked - white
item7 - not clicked - green
item8 - not clicked - white
item9 - not clicked - white
etc...

And that pattern continues for all of the list.

Additionally, if I flick/move the list up and down fast, the pattern shitfs up or down with 1 to 2 items.

Here's a screenshot: List Problem

First image: Nothing is done
Second image: I clicked 'AK Kusine'
Third image: I scroll down, and 'Allan Malka' is also changed..

If I set a breakpoint in the Listener it only stops once per click on the list. What causes this behaviour? And more important, how can I fix it?

3

3 Answers

1
votes

This is because getView method recycle your views to optimize the performance. Implement the getView(int position, View convertView, ViewGroup parent)method in your adapter(so you need to extend an Adapter) in a way that it gets the convertView and makes it green or white according to the position..

Watch this for detailed explanation. It may seem long but it's very useful.

0
votes

It's probably due to something screwing up when it repaints the ListView. Generally, it's better if you just were to set some kind of flag at your data indicating it should be green, and then in your ListView.getView() you'd have something like this

if(listItem.isGreen())
    view.setColor(Color.GREEN);
0
votes

i believe its because android reuses the views in listview to minimize memory foot-print. When you pick first item shown in list, its textview is set to green, but when you scroll the list and first item is invisible, then actually its appearing again as your 7th item and still with its text set to green. To avoid this, you may simply (by default) set your textview to white color in getView of your adapter and hope it should work