如何使用Android ListView setOnScrollListener?

时间:2016-03-21 07:07:26

标签: android listview

我试图在列表末尾滚动时增加整数的值。如果我有5个数字并在列表视图中的最后一项末尾滚动那段时间我必须检查并向上滚动5次直到条件满足。

这是我的代码

listView.setOnScrollListener(new AbsListView.OnScrollListener()
            {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {}

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                                     int visibleItemCount, int totalItemCount)
                {

                    lastInScreen = firstVisibleItem + visibleItemCount;
                    //Log.e("","lastInScreen="+lastInScreen);
                    if(lastInScreen == totalItemCount)
                    {
                        Toast.makeText(getApplicationContext(), "Your Last Item." + lastInScreen , Toast.LENGTH_SHORT).show();
                        if(num < 5)
                        {
                            num += 1;

                            Log.e("","num = "+num );
                        }
                        if(num  == 5)
                        {
                            Log.e(""," Stop Scrolling!!! ");
                        }
                    }
                }
            });

但问题是当我第一次在listview项目末尾滚动时numfor循环时增加到5,我不想这样做。我希望如果我先滚动num增加1,如果我再次滚动,num增加2,因为它最多为5。

1 个答案:

答案 0 :(得分:1)

尝试保存&#34; firstVisibleitem&#34;并且,如果它是相同的,不要做总和。

int X=-1;
listView.setOnScrollListener(new AbsListView.OnScrollListener()
            {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {}

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                                     int visibleItemCount, int totalItemCount)
                {
                    lastInScreen = firstVisibleItem + visibleItemCount;
                    //Compare X with the firstVisibleItem (if X is -1, it always go for false, if X is not -1 X will be the last first visible item
                    if(X!=firstVisibleItem)
                    {
                        if(lastInScreen == totalItemCount)
                        {
                            Toast.makeText(getApplicationContext(), "Your Last Item." + lastInScreen , Toast.LENGTH_SHORT).show();
                            if(num < 5)
                            {
                                num += 1;
                                Log.e("","num = "+num );
                            }
                            if(num  == 5)
                            {
                                Log.e(""," Stop Scrolling!!! ");
                            }
                        }
                    }
                    //Set the value of this firstVisibleItem to X
                    X=firstVisibleItem;
                }
            });