There is a ListView containing, for example, a shopping list. When tapes on a particular element, it is highlighted. How to set the default item? In order for a user to switch to a new activation, see the shopping list and the item selected by default?

  • The question is not clear - what does "the default selected in another activation" mean? You do not know how to transfer values ​​between activations? - Yuriy SPb
  • @Yuriy SPb, that is not the question. I want any element to be highlighted by default, the transition between activations does not play any role here. So that, for example, a user, when clicking on the "shopping list" button, gets to a new activation with a ListView, in which there is already one element selected by default, and, accordingly, highlighted. - Oleksandr Zakrevskyi 2:12 pm
  • Those. You do not know how to highlight? ... - YuriySPb
  • @Yuriy SPb, I know how to highlight, but how to assign the element highlighted by default, that is, SELECTED by default, I don’t know how to do it now - Oleksandr Zakrevskyi

1 answer 1

First, you need to change the choiceMode , specify the color in the listSelector

 <ListView android:id="@+id/list" android:choiceMode="singleChoice" android:listSelector="твой цвет"/> 

And in OnCreate after initializing the list:

 list.setItemChecked( 0, true ); \\ 0 это позиция в списке, отсчёт ведётся с 0. 

And you can also specify the selector:

item_background_selector.xml

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_activated="true" android:color="#0094CE"> </item> <item android:state_pressed="true" android:color="#0094CE"> </item> <item android:state_pressed="false" android:color="#ACD52B"> </item> </selector> 
  • Probably not list.setItemChecked( 0, true ); , and at least to clarify that zero is not just here, but the position in the list that needs to be highlighted (in this case, the first element of the list, since the position count starts from zero) - pavlofff
  • Exactly, thanks, I somehow did not think. - Vladimir VSeos