7

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?

Chad Schultz
  • 7,770
  • 6
  • 57
  • 96

2 Answers2

12

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

Eyal
  • 516
  • 6
  • 9
  • Please note that ``smoothScrollToPositionFromTop()'' has a known bug. See http://stackoverflow.com/questions/14479078/smoothscrolltopositionfromtop-is-not-always-working-like-it-should/#20997828 for the problem and solution. – Lars Blumberg Jan 08 '14 at 14:05
4

Use

setSelection (int position)
gwvatieri
  • 5,133
  • 1
  • 29
  • 29
  • You know, I would have sworn I tried that and it didn't scroll the list. Lo and behold, it does jump the list with the correct row at the top of the screen, which is great! I'm concerned about potential undesirable side effects of that approach, since it wasn't intended for this purpose, and it would be nice to have a smooth scroll instead of the sudden jump... so I'm still accepting answers if anyone has a better solution. Thanks for the prompt answer, gwa, I'll fall back on that if necessary. :) – Chad Schultz Nov 23 '11 at 17:27
  • No problem Chad! I use it in my app and so far it worked pretty well. Let me know in case you find something better. Thanks! – gwvatieri Nov 23 '11 at 18:06