Search code examples
androidandroid-listviewandroid-adapteronscrolllistener

Keep current scroll position when update listview


I want to get new data and update it into my listView using the code below, What i want is when i scroll until the bottom of the listView, it will automatically update and add new data into the list.

E.g: like facebook, only add new data to the bottom without scroll and keep the current position

But i was end up to having some problem. Which are

1) the listview is updated,but it scrolled back to the top.

listview .setOnScrollListener(new OnScrollListener() {
    private int currentVisibleItemCount;
    private int currentScrollState;
    private int currentFirstVisibleItem;
    private int totalItem;

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        this.currentScrollState = scrollState;
        this.isScrollCompleted();
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        this.currentFirstVisibleItem = firstVisibleItem;
        this.currentVisibleItemCount = visibleItemCount;
        this.totalItem = totalItemCount;

    }
    private void isScrollCompleted() {

        if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
                && this.currentScrollState == SCROLL_STATE_IDLE) {

            Log.d("this is", "the end");
            page = page + 1;
            call_function(page);

        }

    }
});

....
....
public void call_function(int page_number) {
...
...
    ListAdapter adapter = new SimpleAdapter(
                            getActivity(), user_List,
                            R.layout.user, new String[] {"user","date"},
                            new int[] {R.id.usr_name ,R.id.register_time});

    // updating listview

    setListAdapter(adapter);
}

any solution to handle this exceptions??

thanks in advance.


Solution

  • When you update your Adapter's data you can save the list current selected item index and set it back when the data is rendered. Something like this:

    int index = mList.getFirstVisiblePosition();
    // do your update stuff
    mList.smoothScrollToPosition(index);