简体   繁体   中英

Why does calling Android ListView's setOnScrollListener immediately call the listener even though there was no scrolling?

Setting a scroll listener on an Android AbsListView causes that listener to be invoked immediately. This is clearly intentional from the source of AbsListView.java :

public void setOnScrollListener(OnScrollListener l) {
    mOnScrollListener = l;
    invokeOnItemScrollListener();
}

Why would anyone want this?

Setting a click/touch listener doesn't cause the listener to be called immediately, why are scroll listeners different? Is there some reasonable rationale for this that I'm missing?

Related question in which someone's bitten by this weird behavior: onScroll gets called when I set listView.onScrollListener(this), but without any touch

So that the scroll listener is informed of the initial position of the list. Because a list is always scrolled to somewhere (even if just 0) while clicks and touches aren't always occurring.

In the end it was just a design decision where they could have gone either way. Its not an uncommon one- lots of GUI frameworks will immediately call listeners on registration if there is data available. If that screws you up, code your listener to ignore the first call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM