I have a listview which displays several items. Now I want to scroll to some specific item (e.g. the 33th item). I know that this can be done via
myList.setSelection(32);
But on the UI the item doesn't receive any highlighting (because it is in touch mode?!). How can I apply a specific background color for this item? I tried
myList.getSelection().getSelectedView().setBackgroundColor(Color.Red);
but i get a NullPointerException because getSelectedView() returns null. Is there a way to achieve this highlighting? I have to notify the user somehow about which item is the "active" one...
Probably the easiest way is to use a State List Drawable for your background. This enables you to apply different styles depending on whether the control in question is selected / focused / disabled / etc.
For an introduction to State List Drawables, have a look at this article.
The nullPointerException is probably because you're in touchmode, setSelection doesn't really selects the item on the listView when you're in touch mode, it just "looks" at it, if you know what i mean.
You Gotta do a customized Adapter (by creating a class that extends the adapter you're currently using :] )
And at your custom adapter class you must override the getView(int position, View convertView, ViewGroup parent) method, like this:
In the code, the variable "lista" is a list of some items i have on my adapter.
So, when you're done selecting your item, you gotta call the getView for every item you have, or you can call the method invalidateViews from your listView before you set the selection (if you call invalidateViews after the selection, the selection will be ignored (at least on touchmode :] ))
Change the line
to
2.To apply a specific color to an item. You can use customized listItem.
a. Set customized lisItem for your listView:
b. In your layout folder, create customizedlistitem.xml
c. In your drawable folder, create customizedbackground.xml like this:
d. Make sure color RED, GREEN and BLACK was defined in your project (you can define it in color.xml under values folder):
ListView in xml file:
Create new xml with listselector name like:
Create colors.xml file like:
In your java code:
Try this, it will work-