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?
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);
lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL)
. Don't do that... it will forcefully scroll to the bottom of your listview until you've pulled most of your hair out. hah. –
Footstool listView
class? And where do I put this code, right after listViewObj.setAdapter(adapter)
? –
Diocese The situation:
When you set an adapter to your listview, it refreshes its state. So, normally scrolls up automatically.
The solution:
Assign an adapter to listview if it has not any, else only update the dataset of the assigned adapter, not re-set it to your listview.
A detailed tutorial is explained at the following link;
Android ListView: Maintain your scroll position when you refresh
Good Luck!
I implemented the postDelayed and I was getting flickering upon refresh. I search some more and found out that I was doing things wrong. Basically I should not create a new adapter every time I wanted to change the data. I ended up doing it this way 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.
I am using
listView.getFirstVisiblePosition
to maintain last visible position.
Try this
boolean first=true;
protected void onPostExecute(Void result)
{
if (first == true) {
listview.setAdapter(customAdapter);
first=false;
}
else
customAdapter.notifyDataSetChanged();
}
Here is the code:
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
© 2022 - 2024 — McMap. All rights reserved.