Chad Schultz
Chad Schultz

Reputation: 7860

smoothScrollToPositionFromTop for Froyo ListView?

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?

Upvotes: 7

Views: 4443

Answers (2)

Eyal
Eyal

Reputation: 516

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);
}

Upvotes: 12

gwvatieri
gwvatieri

Reputation: 5183

Use

setSelection (int position)

Upvotes: 4

Related Questions