Android: ListView.getScrollY() - does it work?

。_饼干妹妹 提交于 2019-11-26 12:47:02

问题


I am using it, but it always returns 0, even though I have scrolled till the end of the list.


回答1:


getScrollY() is actually a method on View, not ListView. It is referring to the scroll amount of the entire view, so it will almost always be 0.

If you want to know how far the ListView's contents are scrolled, you can use listView.getFirstVisiblePosition();




回答2:


It does work, it returns the top part of the scrolled portion of the view in pixels from the top of the visible view. See the getScrollY() documentation. Basically if your list is taking up the full view then you will always get 0, because the top of the scrolled portion of the list is always at the top of the screen.

What you want to do to see if you are at the end of a list is something like this:

public void onCreate(final Bundle bundle) {
     super.onCreate(bundle);
     setContentView(R.layout.main);
     // The list defined as field elswhere
     this.view = (ListView) findViewById(R.id.searchResults);
     this.view.setOnScrollListener(new OnScrollListener() {
          private int priorFirst = -1;
          @Override
          public void onScroll(final AbsListView view, final int first, final int visible, final int total) {
               // detect if last item is visible
               if (visible < total && (first + visible == total)) {
                    // see if we have more results
                    if (first != priorFirst) {
                         priorFirst = first;
                         //Do stuff here, last item is displayed, end of list reached
                    }
               }
          }
     });
}

The reason for the priorFirst counter is that sometimes scroll events can be generated multiple times, so you only need to react to the first time the end of the list is reached.

If you are trying to do an auto-growing list, I'd suggest this tutorial.



来源:https://stackoverflow.com/questions/2132370/android-listview-getscrolly-does-it-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!