Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retaining position in ListView after calling notifyDataSetChanged

I'm using an OnScrollListener to dynamically add items to a ListView when the user scrolls to the bottom. After I add the data to the adapter and call notifyDataSetChanged though, the ListView goes back up to the top. Ideally, I would like to retain the position in the ListView. Any thoughts on how I should go about doing this?

like image 335
SeanPONeil Avatar asked Nov 26 '11 03:11

SeanPONeil


1 Answers

Could this be what you want?

// save index and top position int index = mList.getFirstVisiblePosition(); View v = mList.getChildAt(0); int top = (v == null) ? 0 : v.getTop();  // notify dataset changed or re-assign adapter here  // restore the position of listview mList.setSelectionFromTop(index, top); 

EDIT 28/09/2017:

The API has changed quite a bit since 2015. It is similar, but now it would be:

// save index and top position int index = mList.FirstVisiblePosition; //This changed View v = mList.getChildAt(0); int top = (v == null) ? 0 : v.Top; //this changed  // notify dataset changed or re-assign adapter here  // restore the position of listview mList.setSelectionFromTop(index, top); 
like image 74
iCantSeeSharp Avatar answered Sep 28 '22 12:09

iCantSeeSharp