Saving a position in a ListView after calling notifyDataSetChanged

I use OnScrollListener to dynamically add items to the ListView when the user scrolls down. After adding data to the adapter and calling notifyDataSetChanged, although the ListView returns to the top. Ideally, I would like to keep the position in a ListView. Any thoughts on how I should do this?

+42
android listview
Nov 26 '11 at 3:50
source share
7 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 09/28/2017:

The API has changed quite a bit since 2015. This is similar, but now it will 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); 
+97
Nov 26 2018-11-11T00:
source share

Situation:

When you install the adapter in your list, it updates its status. Thus, it usually scrolls automatically.

Decision:

Assign an adapter to listview if it does not have one, otherwise update only the dataset of the assigned adapter, and do not reinstall it in the list.

A detailed guide is explained at the following link:

Android ListView: keep your scroll position when updating

Good luck

+6
Nov 29 '14 at 7:21
source share

I implemented postDelayed and I started to flicker when upgrading. I was looking for something else and found out that I was doing something wrong. Basically, I don't have to create a new adapter every time I want to change the data. I ended it up like this and it works:

 //goes into your adapter public void repopulateData(String[] objects) { this.objects = null; this.objects = objects; notifyDataSetChanged(); } //goes into your activity or list if (adapter == null) { adapter = new Adapter(); } else { adapter.repopulateData((String[])data); } 

Hope this helps.

0
Dec 03 '14 at 14:45
source share

I use

listView.getFirstVisiblePosition

to save the last visible position.

0
Aug 31 '15 at 16:07
source share

Switch to list transcription mode.

0
Dec 23 '15 at 12:33
source share

try it

  boolean first=true; protected void onPostExecute(Void result) { if (first == true) { listview.setAdapter(customAdapter); first=false; } else customAdapter.notifyDataSetChanged(); } 
0
Jan 09 '16 at 11:12
source share

Here is the code:

 // Save the ListView state (= includes scroll position) as a Parceble Parcelable state = listView.onSaveInstanceState(); // eg set new items listView.setAdapter(adapter); // Restore previous state (including selected item index and scroll position) listView.onRestoreInstanceState(state); 
0
Apr 14 '19 at 17:46
source share



All Articles