Q: Maintain/Save/Restore scroll position when returning to a ListView

D: I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the list to be scrolled to the same point that it was previously. Any ideas on how to achieve this?

Test Case #9


File ID: #3035521-0-cc


public static void bindDataNoRefresh(ListView listView, Runnable runnable) {
    int position = listView.getFirstVisiblePosition();
    View vv = listView.getChildAt(0);
    int tot = 0;
    if (vv ! = null) {
        tot = (int) vv.getScrollY();
    }
    runnable.run();
    listView.setSelectionFromTop(position, tot);
}

  1. This can be made even simpler be using one line to save: `int index = mList.getFirstVisiblePosition();` and only one line to restore: `mList.setSelectionFromTop(index, 0);`. Great answer though (+1)! I have been looking for an elegant solution to this problem.
  2. Not really understanding how this works. I'm using listView.getFirstVisiblePosition() only and understand that, but not sure what's going on here. Any chance of a brief explanation? :)
  3. So ListView.getFirstVisiblePosition() returns the top visible list item. But this item may be partially scrolled out of view, and if you want to restore the exact scroll position of the list you need to get this offset. So ListView.getChildAt(0) returns the View for the top list item, and then View.getTop() returns its relative offset from the top of the ListView. Then, to restore the ListView's scroll position, we call ListView.setSelectionFromTop() with the index of the item we want and an offset to position its top edge from the top of the ListView. All clear?

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: