I know it sounds very simple, and there are questions about this. But none of it could solve my problem. So here we go:
I want to change background color of a list item in a ListActivity
when user clicks on it, and change it back to original color when user clicks again (i.e. Select/Unselect item sort of look)
I tried using getChildAt, it works perfectly if I have all the items visible in one screen without having to scroll.
Code:
getListView().getChildAt(position).setBackgroundColor(Color.CYAN);
The problem begins when I have more items in the list and user has to scroll through them. Once background for an item is changed, The background color shows up on the newly visible items as I scroll. Also, the getChildAt(position)
returns null
(and hence a NullPointerException
) when clicking again on the item.
Can anyone please help me with a simple code that helps me change background color of a list item?
Thanks in advance!
Sure thing. I would do this in the
getView()
method of a customListAdapter
.Update
coloredItems
when a list item is clicked.If you are dealing with
ListFragment
then this code will be helpful,What I do is I create an xml file called i.e. list_background and put it in the drawable folder.
The xml looks like this:
And in the xml code for the ListView's item I put this xml as the items background i.e.
item.xml:
style=@style/Fill is only a short cut i made for android:layout_height="match_parent" and android:layout_width="match_parent
Then in onListItemCLick:
Simply you can do it like this in
onListItemClick
methodthis is how I did it:
create a global variable
View ColoredView
; then when yousetOnItemClickListener
for yourListView
, do this:it's the simplest way in my opinion.
Thanks heycosmo. your solution solved my problem.
Have no clue why we should set background in 2 places.
1. Adapter's getView()
2. ListActivity's onListItemClick().