Maintaining scroll position of a ListView

4373 views
Skip to first unread message

DavidG

unread,
Apr 7, 2009, 10:36:10 AM4/7/09
to Android Developers
In my app, my main class extends ListActivity and calls a fillData()
function to reload the list whenever changes are made. I'm still
getting the hang of this, so I borrowed that concept from the Android
Notepadv1-Notepadv3 tutorials. Everything works great, however
whenever I need to change the list (remove an item, re-sort it, edit
an item), the ListView refreshes and loses its scroll position. The
scroll position is reset to the top after each fillData() call.

I saw the following thread a similar issue, but can't wrap my head
around the solution:
http://groups.google.com/group/android-developers/browse_thread/thread/0b648ce2fe622463/7d40155d450d1196?lnk=raot

It appears to be resetting the scroll position to the top because I'm
using setListAdapter() each time in fillData(), setting it to a new
SimpleCursorAdapter. How can I get the list to "update in place",
where the scroll position is seamlessly maintained to the user? I
tried heading down the "items.changeCursor(cursor)" path, but that
didn't seam to do much for me. Any help would be appreciated. Here's
the code:

private void fillData(boolean sortOption) {
Cursor itemCursor = mDbHelper.fetchAllItems(sortOption);
startManagingCursor(itemCursor);

String[] from = new String[] { DbA.KEY_ITEM, DbA.DESCRIPTION,
DbA.KEY_CHECKED };
int[] to = new int[] { R.id.itemText, R.id.itemDescription,
R.id.content };

SimpleCursorAdapter items = new SimpleCursorAdapter
(this,R.layout.item_row, itemCursor, from, to);
items.setViewBinder(new ItemBinder());
setListAdapter(items);
}

Romain Guy

unread,
Apr 7, 2009, 2:00:01 PM4/7/09
to android-d...@googlegroups.com
ListView handles that already. The problem is that you are creating a
new adapter every time you reload the data. That's not how you should
use ListView and its adapter. Instead of setting a new adapter (which
causes ListView to reset its state), simply update the content of the
adapter already set on the ListView. And the selection/scroll position
will be saved for you.
--
Romain Guy
Android framework engineer
roma...@android.com

Note: please don't send private questions to me, as I don't have time
to provide private support. All such questions should be posted on
public forums, where I and others can see and answer them

Mihai

unread,
Nov 20, 2012, 9:50:59 AM11/20/12
to android-d...@googlegroups.com, roma...@google.com
Hi guys,

I'm having a similar issue on rotating the device, and since the activity, the contained fragment and the list view get re-created on rotate, I don't think Android can take care of retaining the scroll state of the list view. Is there a way to do this without the need to set the activity not to re-create in the manifest?

Best regards,
Mihai
Reply all
Reply to author
Forward
0 new messages