开发者

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 onLoadFinish开发者_StackOverflow中文版ed(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?


Try this:

listView.post(new Runnable() {

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜