Android:检测ScrollView何时滚动到底部

39

可能重复:
如何在 Android 中 scrollView 到达底部时触发事件?

我已经尝试了大约一个小时来检测我的 scrollView 是否到达了屏幕底部。由于涉及到 Android 的各种屏幕大小等问题,我不能简单地说当其 Y 坐标达到某个值时它就到达了底部,但是目前没有找到检测其是否到达底部的方法。

我相信这应该有一个简单的解决方案,比如用某个变量减去视图的高度之类的,但出于某些原因,它对我来说并不容易理解。如果您有任何想法,将不胜感激。谢谢。


不需要扩展ScrollView的简单解决方案:https://dev59.com/22kv5IYBdhLWcg3w1kOq#41139693 - Andrew Koster
1个回答

84

试试这个:

@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) 
{
    // Grab the last child placed in the ScrollView, we need it to determinate the bottom position.
    View view = (View) getChildAt(getChildCount()-1);

    // Calculate the scrolldiff
    int diff = (view.getBottom()-(getHeight()+getScrollY()));

    // if diff is zero, then the bottom has been reached
    if( diff == 0 )
    {
        // notify that we have reached the bottom
        Log.d(ScrollTest.LOG_TAG, "MyScrollView: Bottom has been reached" );
    }

    super.onScrollChanged(l, t, oldl, oldt);
}

为了实现这个功能,需要扩展ScrollView,然后重写从View继承的onScrollChanged方法。
参考:Android: Understanding when ScrollView has reached the bottom

29
根据我的经验,你应该检查if(diff <= 0)。 - littleK
1
如果返回-1,那就有意义。 - BlackHatSamurai
10
仅提供参考,答案是从http://www.marteinn.se/blog/?p=485中复制的。 - Gabor
7
ScrollView 只能容纳一个直接子 View,因此这行代码和 Cast:(View) getChildAt(getChildCount()-1);是不必要的。 - drindt
1
你还可以重写onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)方法,并检查clampedY是否为true。 - Julian
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接