I have a simple ListView
and I want each of it items to be highlighted on user\'s touch. I thought this should happen by default but it isn\'t. Can you advice?
I struggled with this for a few days. In the end, I have to create a widget that supports Checkable
interface and return that widget/view in my adapter's getiew()
function. And the listview needs to be in ListView.CHOICE_MODE_SINGLE
(or possibly any other mode specified by android:choiceMode
) for it to keep track of the choice made on the UI.
So in essence, all the following needs to be in place for the listview item to stay highlighted:
ListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ListAdapter.getView()
return a view that implements Checkable
interfaceListView.OnItemClickListener
should call setItemChecked(position, true)
to mark the item to be checked (and thus highlight it in the listview)Hope this can help someone who is also struggling with this.
I believe this has to do with the "Enabled" attribute of the items in the ListAdapter.
If your Adapter contains the code:
@Override
public boolean areAllItemsEnabled() {
return true;
}
Then each item should be clickable (and therefore should highlight on being touched).
Could you post details (and possibly code) of what kind of Adapter you're using for this list?
You may want to post your actual row layout code, but I suspect the problem will be that you set a background color on your list row. By default, the selectors are drawn behind the list items (which looks nicer, since the highlight color is behind the text). Either don't set a background color on your list items, or set it to draw the selector on top instead with ListView's drawSelectorOnTop XML attribute.
EDIT: If you really must have an opaque background for the default state and don't want to use drawSelectorOnTop
, you can also try this: Set a background on your list rows, but use a StateListDrawable to use @android:drawable/list_selector_background
for all but the default state (you can define an xml file in your drawables folder for this; see the StateList documentation).
You could also nest a layout inside your outer backgrounded row layout with its background set to @android:drawable/list_selector_background
; that way the background would draw on top of your background, but below the content.
ListView
s do not retain a visual indication of focus (or selection) while in touch mode. You will only see this when you use the hardware keyboard or controls to navigate your UI.
See the Google Touch Mode Android Blog article for more details.
So, if you are only using touch mode, you will never see focus or selection on ListView
s.