0

I implemented a ListView, and the method OnItemLongClick to highlight the selected item, but when I select an item, if I scroll the ListView, I find that another item is highlighted.

I'm using this code:

list.setOnItemLongClickListener(new OnItemLongClickListener() {
          public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
              arg1.setBackgroundColor(Color.BLUE);
              return true;
          }
}); 
durron597
  • 31,968
  • 17
  • 99
  • 158
user5174517
  • 301
  • 1
  • 2
  • 6
  • Do you have a header view for your ListView? – pietv8x Jul 30 '15 at 16:05
  • 4
    that's view recycling. don't store state in views. instead, keep something like a selected index, and update the background in the getView of your adapter – njzk2 Jul 30 '15 at 16:05
  • @njzk2 do you mean to use for example: list.getChildAt (pos).setBackround..etc?? Cause also that doesn't work, by the way I don't know how to update the background from the adapter :( – user5174517 Jul 30 '15 at 16:10
  • @pietv8x I use an xml file which xontains a textview and an imageview, I call that file when I devleare the adapter – user5174517 Jul 30 '15 at 16:10
  • 1
    Which kind of adapter are you using? Would you be overriding the BaseAdapter or using an ArrayAdapter? – Unknownweirdo Jul 30 '15 at 16:11
  • absolutely not. never, ever are you to access list elements using `getChildAt`. In the `getView` set the background of the element you are working on, based on whether it is selected or not. – njzk2 Jul 30 '15 at 16:12
  • @Losin' Me I am using the arrayadapter – user5174517 Jul 30 '15 at 16:12
  • @njzk2 so if in OnItemLongClick I have to see if the element is selected and if so I can change the background, and there would be no problem ? – user5174517 Jul 30 '15 at 16:17
  • Hey, try this http://stackoverflow.com/a/17199381/3309883 – Unknownweirdo Jul 30 '15 at 16:17
  • Do not rely on the index of the item, instead change the item on the base list. The indices get recycled and the same indices would get assigned to another item on scroll. Find out the right item from your list based on the property and highlight it. – Sushant kunal Jul 31 '15 at 06:25

1 Answers1

0

you can use android:listSelector property instead of onItemLongClick

Salah Nour ElDin
  • 510
  • 2
  • 13