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

后端 未结 20 2090
無奈伤痛
無奈伤痛 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

    A very simple way:

    /** Save the position **/
    int currentPosition = listView.getFirstVisiblePosition();
    
    //Here u should save the currentPosition anywhere
    
    /** Restore the previus saved position **/
    listView.setSelection(savedPosition);
    

    The method setSelection will reset the list to the supplied item. If not in touch mode the item will actually be selected if in touch mode the item will only be positioned on screen.

    A more complicated approach:

    listView.setOnScrollListener(this);
    
    //Implements the interface:
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
        mCurrentX = view.getScrollX();
        mCurrentY = view.getScrollY();
    }
    
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    
    }
    
    //Save anywere the x and the y
    
    /** Restore: **/
    listView.scrollTo(savedX, savedY);
    

提交回复
热议问题