Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Gridview OnScrollListener ScrollUp and ScrollDown event

I have gridview and I need to do two things:

When I scroll down, I want to find the last visible position e.g int index = GridView.getLastVisiblePosition();

When I scroll up, I want to find the first visible position e.g int index = GridView.getFirstVisiblePosition();

I know I can use the following code, but I'm not sure how and where to write a code for ScrollUp and ScrollDown. Please help me. I am new to Android.

private OnScrollListener onAnswersScrolled = new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }
}
like image 861
Shri Ksai Avatar asked May 04 '13 02:05

Shri Ksai


2 Answers

Create global variable myLastVisiblePos in your activity, and save for each FirstVisiblePosition, when onScroll event check current FirstVisiblePosition with your saved FirstVisiblePosition if greate than your last saved FirstVisiblePosition then scrollUp if small then scrollDown:

int myLastVisiblePos;// global variable of activity

//save first value when you create GridView
GridView gridView = (GridView) gv.findViewById(R.id.grid_view);
myLastVisiblePos = gridView.getFirstVisiblePosition();

gridView.setOnScrollListener( new OnScrollListener() {
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int currentFirstVisPos = view.getFirstVisiblePosition();
            if(currentFirstVisPos > myLastVisiblePos) {
                //scroll down
            }
            if(currentFirstVisPos < myLastVisiblePos) {
                //scroll up
            }
            myLastVisiblePos = currentFirstVisPos;
    }
});
like image 175
SBotirov Avatar answered Oct 14 '22 12:10

SBotirov


Try this Code may be helpful to you..

GridView gridView = (GridView) gv.findViewById(R.id.grid_view);
gridView.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
            Log.e("GridView","firstVisibleItem"+firstVisibleItem+"\nLastVisibleItem"+totalItemCount);
            }
        }
    });
like image 29
Umesh Lakhani Avatar answered Oct 14 '22 13:10

Umesh Lakhani