1

I have listview with custom adapter. In each row i have 2 textviews and a button. I want when I click on an item to highlight it and to stay highlighted until i click another item. I tried to do it with list selector but didn't succeed. Then I tried to do it like this:

public void onClick(View v) {
    ListView lvItems = context.lvLists;
    for (int i=0; i < lvItems.getChildCount(); i++) 
    {
        lvItems.getChildAt(i).setBackgroundColor(Color.BLACK);        
    }
    v.setBackgroundColor(Color.parseColor("#555555"));

This is the onclick of each row of the listview. It works but I saw that when I scroll down there are more items selected (which I didn't select). Solution for this?

nikmin
  • 1,803
  • 3
  • 28
  • 46

3 Answers3

1

If you want to save some properties of your ListView items you can't rely on Views themselves. You have to store them in your data so that your Adapter knows which item's state has changed. See the answer to this question for more details:

Android: Spinners within a ListView loose their values when I add dynamically new ListView entries

Community
  • 1
  • 1
devmiles.com
  • 9,895
  • 5
  • 31
  • 47
0

You should implement the view-holder pattern and then, in your holder code, you can have a (boolean) variable that holds the current state for that item (highlighted or not-highlighted), changing the background color accordingly.

takecare
  • 1,684
  • 3
  • 21
  • 32
  • ViewHolder pattern isn't about storing values, it's only used to hold references to views so that you don't have to call getViewById each time adapter re-uses the view. – devmiles.com Oct 25 '12 at 13:06
0

You have plenty of answers here on Stack Overflow. Try checking this,this and also this.

Community
  • 1
  • 1
slezadav
  • 6,104
  • 7
  • 40
  • 61