我怎么知道scrollview已滚动到底部?

san*_*nna 14 android scrollview

我有一个scrollview,我只想要一个事件发生,如果它已经滚动到底部,但我找不到一种方法来检查滚动视图是否在底部.

我已经解决了相反的问题; 只有在事件已经滚动到顶部时才允许事件发生:

ScrollView sv = (ScrollView) findViewById(R.id.Scroll);
    if(sv.getScrollY() == 0) {
        //do something
    }
    else {
        //do nothing
    }
Run Code Online (Sandbox Code Playgroud)

san*_*nna 9

我找到了一种让它发挥作用的方法.我需要检查孩子的测量高度到ScrollView,在这种情况下是LinearLayout.我使用<=因为它也应该在不需要滚动时执行某些操作.即LinearLayout不如ScrollView那么高.在这些情况下,getScrollY始终为0.

ScrollView scrollView = (ScrollView) findViewById(R.id.ScrollView);
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout);
    if(linearLayout.getMeasuredHeight() <= scrollView.getScrollY() +
           scrollView.getHeight()) {
        //do something
    }
    else {
        //do nothing
    }
Run Code Online (Sandbox Code Playgroud)

  • 由于ScrollView只能有一个子节点,您可以确定其中有一个:if(scrollView.getScrollY()+ scrollView.getHeight()> = scrollView.getChildAt(0).getMeasuredHeight()){/*已滚动到底部*/} (2认同)

Mas*_*shi 5

这里是:

public class myScrollView extends ScrollView
{
    public myScrollView(Context context)
    {
        super(context);
    }
    public myScrollView(Context context, AttributeSet attributeSet)
    {
        super(context,attributeSet);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt)
    {
        View view = (View)getChildAt(getChildCount()-1);
        int d = view.getBottom();
        d -= (getHeight()+getScrollY());
        if(d==0)
        {
            //you are at the end of the list in scrollview 
            //do what you wanna do here
        }
        else
            super.onScrollChanged(l,t,oldl,oldt);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在xml布局中使用myScrollView,也可以在代码中实例化它.提示:使用上面的代码,如果用户频繁点击列表末尾10次,那么您的代码将运行10次.在某些情况下,例如当您想要从远程服务器加载数据以更新列表时,这种行为将是不受欢迎的(最有可能).试着预测不良情况并避免它们.

提示2:有时接近列表末尾可能是让脚本运行的最佳时机.例如,用户正在阅读文章列表,并且已接近尾声.然后你在列表完成之前开始加载更多.为此,请执行此操作以实现您的目的:

if(d<=SOME_THRESHOLD) {}
Run Code Online (Sandbox Code Playgroud)