问题描述
我有gridview,我需要做两件事:
当我向下滚动时,我想查找最后一个可见位置,例如 int index = GridView.getLastVisiblePosition();
当我向上滚动时,我想找到第一个可见的位置,例如 int index = GridView.getFirstVisiblePosition();
我知道我可以使用下面的代码,但我不确定如何以及在何处为ScrollUp和ScrollDown编写代码。请帮帮我。
private OnScrollListener onAnswersScrolled = new OnScrollListener(){
@Override
public void onScrollStateChanged(AbsListView view,int scrollState){
}
}
int myLastVisiblePos; //活动的全局变量
//在创建GridView时保存第一个值
GridView gridView =(GridView)gv.findViewById(R.id.grid_view);
myLastVisiblePos = gridView.getFirstVisiblePosition();
gridView.setOnScrollListener(new OnScrollListener(){
@Override $ b $ public void onScroll(AbsListView view,int firstVisibleItem,int visibleItemCount,int totalItemCount){
int currentFirstVisPos = view.getFirstVisiblePosition();
if(currentFirstVisPos> myLastVisiblePos){
//向下滚动
}
if(currentFirstVisPos< myLastVisiblePos){
//向上滚动
}
myLastVisiblePos = currentFirstVisPos;
}
});
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;
}
});
这篇关于Android Gridview OnScrollListener ScrollUp和ScrollDown事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!