Android ListView: how to select an item?

android, android-listview, android-widget

Solution

The missing element here is `choiceMode`. This isn't terribly well documented, but ListViews (and by extension, anything that inherits from AbsListView, like GridView, etc.) in android by default do not allow for selection, but it can be enabled - either in XML or in code:

in XML:

<ListView
  ...
  android:choiceMode="singleChoice" />

Code:

mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);

Note that once you do this, android will `setSelection()` for you, so you don't need to keep track of it yourself. At that point your onClickListener is just for saving the selection and I don't even bother with the OnSelectedItemListener :

@Override
public void onItemClick(final AdapterView<?> list, final View v,
    final int position, final long id) {
  Participant p = mAdapter.getParticipantForId(id);
  eventManager.fire(new ParticipantSelectedEvent(p));
  pxList.smoothScrollToPosition(position); // Make sure selection is plainly visible
}

Problem

I am having trouble with a ListView I created: I want an item to get selected when I click on it. My code for this looks like: ``` protected void onResume() { ... ListView lv = getListView(); lv.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) { Log.v(TAG, "onItemSelected(..., " + pos + ",...) => selected: " + getSelectedItemPosition()); } public void onNothingSelected(AdapterView<?> adapterView) { Log.v(TAG, "onNothingSelected(...) => selected: " + getSelectedItemPosition()); } }); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) { lv.setSelection(pos); Log.v(TAG, "onItemClick(..., " + pos + ",...) => selected: " + getSelectedItemPosition()); } }); ... } ``` When I run this and click e.g. on the second item (i.e. pos=1) I get: ``` 04-03 23:08:36.994: V/DisplayLists(663): onItemClick(..., 1,...) => selected: -1 ``` i.e. even though the OnItemClickListener is called with the proper argument and calls a setSelection(1), there is no item selected (and hence also OnItemSelectedListener.onItemSelected(...) is never called) and getSelectedItemPosition() still yields -1 after the setSelection(1)-call. What am I missing? Michael PS.: My list does have >=2 elements...

Original source