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) {
}
}
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;
}
});
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With