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

后端 未结 20 1685
無奈伤痛
無奈伤痛 2020-11-21 21:30

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

20条回答
  •  醉酒成梦
    2020-11-21 22:03

    For an activity derived from ListActivity that implements LoaderManager.LoaderCallbacks using a SimpleCursorAdapter it did not work to restore the position in onReset(), because the activity was almost always restarted and the adapter was reloaded when the details view was closed. The trick was to restore the position in onLoadFinished():

    in onListItemClick():

    // save the selected item position when an item was clicked
    // to open the details
    index = getListView().getFirstVisiblePosition();
    View v = getListView().getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - getListView().getPaddingTop());
    

    in onLoadFinished():

    // restore the selected item which was saved on item click
    // when details are closed and list is shown again
    getListView().setSelectionFromTop(index, top);
    

    in onBackPressed():

    // Show the top item at next start of the app
    index = 0;
    top = 0;
    

提交回复
热议问题