本文介绍了Android Gridview OnScrollListener ScrollUp和ScrollDown事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有gridview,我需要做两件事:

当我向下滚动时,我想查找最后一个可见位置,例如 int index = GridView.getLastVisiblePosition();



当我向上滚动时,我想找到第一个可见的位置,例如 int index = GridView.getFirstVisiblePosition();



我知道我可以使用下面的代码,但我不确定如何以及在何处为ScrollUp和ScrollDown编写代码。请帮帮我。

  private OnScrollListener onAnswersScrolled = new OnScrollListener(){

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


myLastVisiblePos ,并保存每个FirstVisiblePosition,当onScroll事件检查当前FirstVisiblePosition与您保存的FirstVisiblePosition如果比上次保存的FirstVisiblePosition更大,那么scrollUp if small然后scrollDown:

  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事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:57