Sotti
Sotti

Reputation: 14389

Highlight the first element in a listview when it's shown

I have a listview. On each element of the listview you can touch and it triggers something (ie a toast). Each time you touch on any element it must remain highlighted.

I want that the first element in the listview to appear highlighted by default the first time the listview is showed, this is when you launch the app.

Right now I have all working except the highlight in the first element the first time. I mean, the element is even triggered but is not highlighted when you launch the app.

Any ideas?

I've tried a lot of thiings that I've read on stackoverflow but non worked and I think should be something very common.

I've tried setSelection, setSelected, getting the view.....

I though it worked like the spinner but it's not.

Thanks a lot guys!!

You can check the class code here --> http://goo.gl/ndY0Ni

If any of you want to try it, I've made a simpler example --> https://dl.dropboxusercontent.com/u/83259317/main.rar

SOLUTION: Thanks to @Jiahao to provide a solution.

I've made a little proyect in order to you check it out --> http://goo.gl/35s5Dc

Upvotes: 1

Views: 446

Answers (2)

jiahao
jiahao

Reputation: 3393

SetItemChecked works for the list. The problem is when your row view is not an instance of Checkable, it is not shown.

Instead, a stated callled "Activated" will be marked.

The easiest solution is customize the rowView to show the state Activated:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:drawable="@drawable/listview_selector_pressed"/>
    <item
        android:state_pressed="true"
        android:drawable="@drawable/listview_selector_pressed"/>
    <item
        android:state_activated="true"
        android:drawable="@drawable/listview_selector_pressed"
        />
    <item
        android:drawable="@android:color/white" />
</selector>

Upvotes: 1

VM4
VM4

Reputation: 6501

To set a ListView Item as highlighted you use this code:

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Highlight one at a time.
getListView().setItemChecked(position, true);

Where position is the number of the ListItem you want to hightlight, So to highlight the first item you do:

  getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  getListView().setItemChecked(0, true);

This is assuming you are using a ListActivity. (If not just call the methods on the actual ListView Object).

Upvotes: 0

Related Questions