Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a ListView on its current selection

Tags:

android

Does anyone know of a way to center a ListView based on its current selection or selection set with setSelection?

I did see this other StackOverflow question without any answers: Android ListView center selection

Thanks, Kevin

like image 435
Kevin Parker Avatar asked Apr 04 '11 14:04

Kevin Parker


3 Answers

First, get the height of the ListView using getHeight, which returns the height of the ListView in pixels.

Then, get the height of the row's View using the same method.

Then, use setSelectionFromTop and pass in half of the ListView's height minus half of the row's height.

Something like:

int h1 = mListView.getHeight();
int h2 = v.getHeight();

mListView.setSelectionFromTop(position, h1/2 - h2/2);

Or, instead of doing the math, you might just pick a constant for the offset from the top, but I would think it might be more fragile on different devices since the second argument for setSelectionFromTop appears to be in pixels rather than device independent pixels.

I haven't tested this code, but it should work as long as your rows are all roughly the same height.

like image 93
Brian Cooley Avatar answered Nov 08 '22 03:11

Brian Cooley


You will need to have the scroll view and the view of the item selected. Then you can simply do:

scrollView.smoothScrollTo(0, selectedView.getTop() - (scrollView.getHeight() / 2) + (selectedView.getHeight() / 2), 0);

This will center the scroll view exactly on selectedView

like image 24
Luke Sleeman Avatar answered Nov 08 '22 02:11

Luke Sleeman


I haven't tried any of this but based on the current selection could you use public void smoothScrollByOffset (int offset) to get the view to scroll to where you want so that your selection is in the middle of the view?

like image 38
Chris Avatar answered Nov 08 '22 01:11

Chris