Is there a way to prevent the listview from scrolling to its top position when its adapter's data is changed?

前端 未结 4 1156
無奈伤痛
無奈伤痛 2020-12-09 03:43

I\'m having a bit of trouble preserving the scroll position of a list view when changing it\'s adapter\'s data.

What I\'m currently doing is to create a custom Array

4条回答
  •  忘掉有多难
    2020-12-09 04:14

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

    Use this to save the position in the ListView before you call .clear(), .addAll(), and . notifyDataSetChanged().

    int index = mList.getFirstVisiblePosition();
    View v = mList.getChildAt(0);
    int top = (v == null) ? 0 : v.getTop();
    

    After updating the ListView adapter, the Listview's items will be changed and then set the new position:

    mList.setSelectionFromTop(index, top);
    

    Basically you can save you position and scroll back to it, save the ListView state or the entire application state.

    Other helpful links:

    Save Position: How to save and restore ListView position in Android

    Save State: Android ListView y position

    Regards,

    Please let me know if this helps!

提交回复
热议问题