NullPointerException
NullPointerException

Reputation: 37577

How to highlight an item of a listview programmatically?

I have a listview and I need to highlight a item programmatically.

I tried with this:

CalendarList = (ListView) findViewById(R.id.CalendarList);
CalendarList.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, MyApplication.roundMatches(CalendarPicker.getValue())));

CalendarList.setSelection(2);

but setSelection didn't work.

Upvotes: 1

Views: 2566

Answers (4)

NullPointerException
NullPointerException

Reputation: 37577

finally none of these solutions works, i did this by a different way, changing the colour of the text of the selected item

Upvotes: 2

Vector
Vector

Reputation: 359

To highlight an item in touch mode you have to first call CalendarList.requestFocusFromTouch(); then CalendarList.setSelection(2);

In touch mode setSelection() doesn't work by itself.

Upvotes: 3

NguyenDat
NguyenDat

Reputation: 4159

Try to override onScroll() method:

@Override
public void onScroll(AbsListView listView, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
    /* Get view of item in list */
    View view = listView.getSelectedView();
    }

When have view object of list view you can change what ever you want, notice you must implement code for handle when lost focus.

Otherwise, i think have another solution is change color of item via implement of Adapter. Regards,

Upvotes: 0

Nikola Despotoski
Nikola Despotoski

Reputation: 50538

You want the highlighting on click?

Then override the onItemClickedListener()

and do this inside:

position = position - listview.getFirstVisibleItem();
listview.getChildAt(position).requestFocus(); 

or make use of <selector.

Upvotes: 1

Related Questions