Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smoothScrollToPositionFromTop for Froyo ListView?

Tags:

android

I want to tap a control on the screen and have the ListView scroll until a given row is at the TOP of the screen, a feature that appears to be very easy in iOS.

I did find such a method in the API: http://developer.android.com/reference/android/widget/AbsListView.html#smoothScrollToPositionFromTop(int, int) However, this is for API Level 11, Honeycomb. That means phones can't use it until Ice Cream Sandwich, and it will be a long, long time until it's practical to set Ice Cream Sandwich as a minimum requirement to run apps.

Is there a way to get this same functionality in Froyo?

like image 502
Chad Schultz Avatar asked Nov 23 '11 17:11

Chad Schultz


2 Answers

The following code is not perfect, but it does the work in many cases:



if (android.os.Build.VERSION.SDK_INT >= 11)
{
    listView.smoothScrollToPositionFromTop(p, 0); 
}
else if (android.os.Build.VERSION.SDK_INT >= 8)
{
    int firstVisible = listView.getFirstVisiblePosition();
    int lastVisible = listView.getLastVisiblePosition();
    if (p < firstVisible)
        listView.smoothScrollToPosition(p);
    else
        listView.smoothScrollToPosition(p + lastVisible - firstVisible - 2);
}
else
{
    listView.setSelectionFromTop(p, 0);
}

like image 182
Eyal Avatar answered Nov 08 '22 09:11

Eyal


Use

setSelection (int position)
like image 45
gwvatieri Avatar answered Nov 08 '22 08:11

gwvatieri