ThatBoiJo
ThatBoiJo

Reputation: 319

Highlight selected ListView item

Okay so I've been able to hightlight an item in a ListView, but it ends up highlighting every fourth item. I'm pretty sure that's because of recycling. Then I had the issue where the highlighted item would go back to normal after I scrolled, and that's also because of recycling. Is there any way to keep it highlighted, or to maybe stop the ListView from recycling?

This is what the code looks like right now...

runTimes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> list, View v, int pos, long id) {     
                v.setSelected(true);

        }
    });

This is the code where the highlighted item goes back to normal after you scroll.

Upvotes: 1

Views: 637

Answers (3)

ThatBoiJo
ThatBoiJo

Reputation: 319

I ended up finding another question that helped me figure out how to do it. This is what I did. In the OnClickListener I check to see if something has been pressed before. If it hasn't been pressed before, then I set the views background color, and prevRunView to the view. If something has been pressed before, then I change the previous view background color to white. After that I do the same thing as before, but for the different view.

if(runIndex == -1){
                runIndex = pos;
                v.setBackgroundColor(Color.parseColor("#A6A6A8"));
                prevRunView = v;
            }else{
                prevRunView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                runIndex = pos;
                v.setBackgroundColor(Color.parseColor("#A6A6A8"));
                prevRunView = v;
            }

In my adapter I wrote this code so it won't seem like it's recycling.

if(ScoreActivity.runIndex == position)
        v.setBackgroundColor(Color.parseColor("#A6A6A8"));
    else
        v.setBackgroundColor(Color.parseColor("#FFFFFF"));

Upvotes: 0

tyczj
tyczj

Reputation: 73721

to hilight a row you should not touch the view at all. you should use listviews setItemChecked with a selector as the background of your view.

runTimes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> list, View v, int pos, long id) {     
                runTimes.setItemChecked(pos,true);

        }
    });

you also need to make sure you keep track of the last position you selected so that you can deselect it when you select a new one

Upvotes: 2

Simas
Simas

Reputation: 44118

If you want to stop ListView from recycling you should think again if you really need a ListView.

To properly accomplish this with a ListView, though, you need to save the highlighted item states inside of your adapter. Then in getView highlight the items based on their position.

There have been A LOT of questions about saving the state of the ListView items, I'm sure you can find some.

Upvotes: 1

Related Questions