Adding items to ListView, maintaining scroll position and NOT seeing a scroll jump

前端 未结 3 1729
暗喜
暗喜 2021-01-31 04:23

I\'m building an interface similar to the Google Hangouts chat interface. New messages are added to the bottom of the list. Scrolling up to the top of the list will trigger a lo

3条回答
  •  死守一世寂寞
    2021-01-31 04:46

    I was breaking up my head until I found a solution similar to this. Before adding a set of items you have to save top distance of the firstVisible item and after adding the items do setSelectionFromTop().

    Here is the code:

    // save index and top position
    int index = mList.getFirstVisiblePosition();
    View v = mList.getChildAt(0);
    int top = (v == null) ? 0 : v.getTop();
    
    // for (Item item : items){
        mListAdapter.add(item);
    }
    
    // restore index and top position
    mList.setSelectionFromTop(index, top);
    

    It works without any jump for me with a list of about 500 items :)

    I took this code from this SO post: Retaining position in ListView after calling notifyDataSetChanged

提交回复
热议问题