androidscrollviewandroid-viewscroll-position

Scroll position is not saved in Grdiview


Can somebody please help me I have an issue in scroll of GridView What I do is I show the first 10 products in GridView from the API.. Now what I need is - When the user scrolls and gets the last position of list then API hits again with page value 2 .. and the scroll shows from the current position where the user is.. Now Data is shown and Adapter changes its value.. But scroll shows on the top when the new API hits... Can anyone please tell me What is to be done??? Really Appreciated please help..

what I do -

        grid.setOnScrollListener(new AbsListView.OnScrollListener() {
        int last_item;

        @Override
        public void onScrollStateChanged(AbsListView view, int   scrollState) {

        }

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


            int lastitem = firstVisibleItem + visibleItemCount;
            if(lastitem == totalItemCount){

                       HitApi();//This is the method where API hits with the new page value


            }


        }
    });

xml file

       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"

       xmlns:android="http://schemas.android.com/apk/res/android">


        <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/products_GridView"
        android:numColumns="auto_fit"
        android:listSelector="@android:color/transparent"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        >
       </GridView>


        </LinearLayout>

Solution

  • Okay so assuming that hitApi() updates the ListView with the new items, then the method will probably call .clear() on the current list which will cause the problem and then it will add the new items; what you have to do here to keep the last position is adding this before hitApi() method:

    int i = yourList.getFirstVisiblePosition();
    View v = yourList.getChildAt(0);
    int t = 0;
    if(v!=null)v.getTop();
    

    Then after calling the hitApi() method, set up the old position back:

    yourList.setSelectionFromTop(i, t);