num1
num1

Reputation: 4975

Scrolling a ListView to a position after cursor loads

I have a fragment with a ListView, and I want the ListView to maintain its scroll position when the fragment is saved and restored. Usually this is easy, just call ListView.getFirstVisiblePosition() when saving and ListView.setSelection() (ListView.setSelectionFromTop() if you want to get fancy) when restoring.

However, I'm using loaders, and my ListView isn't fully populated when the activity starts. If I setSelection() during onActivityCreated() the list won't have anything to scroll to yet, and the call will be ignored.

I'm getting around this now by posting the scroll for sometime in the future, but this definitely isn't ideal. I'd prefer for it to scroll right as the data finishes loading. I'm almost doing that here, but swapCursor() doesn't refresh, it just schedules an invalidation for the future.

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mAdapter.swapCursor(data);
    if (savedScrollPosition != null) {
        Log.d(TAG, "loaded and scrolling to " + savedScrollPosition);
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                list.setSelection(savedScrollPosition);
                savedScrollPosition = null;
            }
        }, 100);
    }
}

Do you know of any way of scrolling the ListView right as the ListView finishes populating with data?

Upvotes: 4

Views: 4265

Answers (1)

Shafi
Shafi

Reputation: 1368

Try this:

listView.post(new Runnable() {

        @Override
        public void run() {
            listView.setSelection(savedScrollPosition);
            savedScrollPosition = null;
        }
    });

Upvotes: 7

Related Questions