Search code examples
javaandroidlistviewcentering

Centering a list item on the screen when selected in Android?


I have a listView and a timer iterates through each list item. Ideally I'd like to have the currently selected item to automatically center in the listView. I've played around with smoothScrollToPosition() but am lost on how to work out centering the current item.

My corrected code (thanks to Matej Spili):

// Smooth scroll the list item 
try {
scrollView.smoothScrollBy(scrollView.getChildAt().getTop(‌​) - (scrollView.getHeight() / 2) + (scrollView.getChildAt().getHeight() / 2), 1500);
} 
catch (NullPointerException e)
{ 
System.out.println("NULL POINTER DEALT WITH");
}

Solution

  • 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.

    Or in one line:

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