Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView center selection

Tags:

java

android

I have a ListView that shows the closest word matches to a search.

For example if I search "hi" I get the following results in the ListView


...
hi
hi five
hi-five
high
highlight
....

I am using

ListView.setSelection(wordList.indexOf(searchWord));
ListView.setSelected(true);

The above code puts the selected word "hi" at the top and doesnt highlight the selection.

I want the "hi" to be centrally positioned , selected and highlighted automatically. See below

...
hello
hello there
hi
hi-five
hi five
...

What code can I use to achieve the above?

Many thanks.

like image 315
Consilium Software Avatar asked Nov 26 '22 19:11

Consilium Software


1 Answers

ListView view = (ListView)findViewById(R.id.YourListView);

int height = view.getHeight();
int itemHeight = view.getChildAt(0).getHeight();
view.setSelectionFromTop(position, height/2 - itemHeight/2);

The position (int) is the listitem you want to center in the listview!!

like image 104
The Fettuck Avatar answered Feb 09 '23 01:02

The Fettuck