7

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

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

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

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

private OnScrollListener onAnswersScrolled = new OnScrollListener() {

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

2 回答 2

23

在您的活动中创建全局变量myLastVisiblePos,并为每个 FirstVisiblePosition 保存,当 onScroll 事件检查当前 FirstVisiblePosition 与您保存的 FirstVisiblePosition 如果大于您上次保存的 FirstVisiblePosition 然后 scrollUp 如果小然后 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;
    }
});
于 2013-05-04T05:12:13.863 回答
2

试试这个代码可能对你有帮助..

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);
            }
        }
    });
于 2013-05-04T03:41:16.307 回答