简体   繁体   English

如何检测scrollview的孩子到达屏幕顶部?

[英]how to detect child of scrollview reached top of screen?

I have ScrollView with many views , how can I know if specific view reached to top of screen after scroll? 我有很多视图的ScrollView,如何知道滚动后特定视图是否到达屏幕顶部?

I tried this 我试过了

mScroll.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {

            @Override
            public void onScrollChanged() {

                Rect scrollBounds = new Rect();
                mScroll.getHitRect(scrollBounds);

                if (mView.getLocalVisibleRect(scrollBounds) ) {

                    // if layout even a single pixel, is within the visible area do something
                    //Do someThing
                } else {

                    // if layout goes out or scrolled out of the visible area do something
                    // Do some thing
                }

            }
        });

But this codes detect if the view is out of screen not top of screen 但是,此代码检测视图是否在屏幕之外而不是在屏幕上方

在与所需位置进行比较之后,使用View.getLocationOnScreen()和/或getLocationInWindow()

You can create a class to custom ScrollView. 您可以创建一个类以自定义ScrollView。 In this class, override method onScrollChanged(int l, int t, int oldl, int oldt); 在此类中,重写方法onScrollChanged(int l,int t,int oldl,int oldt);

this is my code with vertical ScrollView. 这是我的垂直ScrollView代码。

private int rangeEndHeight = 20;
private boolean onEnd = false;

@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    int length = (int) Math.floor(getContentHeight() * getScale());
    if(getScrollY() >= length - getHeight() - rangeEndHeight) {
        if (!onEnd) {
            onEnd = true;

            // callback here

        }
    }
    else {
        onEnd = false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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