Set activated item in ListView programmatically

I have a simple ListView with some elements for which setChoiceMode set to ListView.CHOICE_MODE_SINGLE , which means that when I touch an element, it is highlighted. Thus, the user can see which menu choice ( ListView is a menu):

 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

However, I want to change this selection from the code (without touching). I tried this:

 listView.setSelection(0); 

but it does not seem to have any effect. Probably because selection and activation are different concepts. There is no setActivated(int) method available.

+8
android listview
source share
3 answers

You can select an item with the following code:

 listView.setItemChecked(position, true); 
+17
source share

Using this method worked for me

 listView.performItemClick(listView, position, listView.getItemIdAtPosition(position)); 
+1
source share

The documentation says If in touch mode, the item will not be selected but it will still be positioned appropriately .

So you need to use ListView.setItemChecked(int position, boolean checked) method as listView.setItemChecked(position, true) to set the position as selected

0
source share

All Articles