3

I am trying to implement an appropriate behavior in my Android app if it runs on a device with dPad.

There is an activity with a ListView. The selected item changes properly as a user presses dPad buttons. However, I am trying to set the selected item programatically at a certain point in my Java code. I can achieve this by

myListView.setSelection(position);

That is fine but how should I clear the selection? If no item is selected, the method myListView.getSelectedItemPosition() returns -1. However, I can't call myListView.setSelection(-1) as negative values are ignored by this method.

What is the correct way to unset the selected item?

I am aware of many question on Stack Overflow talking about "selected item in a list view" but they are about radio buttons and single choice, not about dPad navigation.

Cimlman
  • 3,404
  • 5
  • 25
  • 35
  • 1
    Have you tried what the ideas in [this post](http://stackoverflow.com/questions/15081274/clear-singlechoice-listview-selection) such as `myListView.setItemChecked(-1, true);`? – George Mulligan Apr 06 '16 at 14:46
  • @George Mulligan I have tried it according to your suggestion. :) Neither `setItemChecked(-1, true)` nor `clearChoices()` works. As I have mentioned, that post is about single choice selection, not about dPad. – Cimlman Apr 06 '16 at 15:00
  • I understand. But since you mentioned `setSelection(position)` works correctly with positive values it seems you should be able to clear the selection the same way. But apparently not... – George Mulligan Apr 06 '16 at 15:02
  • Just a note: The Javadoc to `setSelection(int)` says: "If the specified selection position is less than 0, then the item at position 0 will be selected." It means that it cannot be used to clear the selection. – Cimlman Apr 06 '16 at 15:05
  • By the same way I wasn't referring to `setSelection(-1)`. I meant the same way as listed in the answers to the question I linked to just to be clear. – George Mulligan Apr 06 '16 at 15:08
  • @Cimlman Try to call *notifyDataSetChanged();* after *clearChoices();* – Rami Apr 06 '16 at 17:35
  • 1
    @Rami Tried `clearChoices` followed by `notifyDataSetChanged`. It has not any effect either. – Cimlman Apr 07 '16 at 11:21

0 Answers0