Android:当ScrollView触及底部时检测

Pea*_*aft 38 android scroll position scrollview

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

我已经尝试了一个小时左右来检测我的scrollView何时到达屏幕的底部.由于各种屏幕尺寸和Android没有涉及的内容,我不能简单地说当它的Y位置达到某个值时它位于底部,但是没有方法可以检测到它在底部是否找到了.

我确信这有一个简单的解决方案,通过其他变量或其他东西减去视图的高度,但由于某种原因它只是没有点击我.任何想法将不胜感激,谢谢.

Har*_*Joy 82

试试这个:

@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);
}
Run Code Online (Sandbox Code Playgroud)

要实现它,请扩展ScrollView然后重写onScrollChanged方法(继承自View).

参考:Android:了解ScrollView何时到达底部

  • 根据我的经验,你应该检查if(diff <= 0) (28认同)
  • 只是为了给予信任,答案是从http://www.marteinn.se/blog/?p=485复制的 (10认同)
  • ScrollView只能托管一个直接子项,所以行和Cast:(View)getChildAt(getChildCount() - 1); 没必要. (7认同)