Search code examples
androidscrollviewandroid-scrollview

Detect the top of a ScrollView


How can I detect the TOP of a ScrollView? I have implemented code to detect the bottom, but I cannot seem to figure out the calculation that determines when the top has been reached.

     @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        int startPosition = t;
        View view = (View) getChildAt(getChildCount() - 1);
        int diff = (view.getBottom() - (getHeight() + getScrollY()));

        if (diff == startPosition){
            oListener.onTopReached();
        } else {
            nListener.BottomNotReached();
        }

/*        if (diff == 0 && mListener != null) {
            mListener.onBottomReached();
        } else if (diff == getTop()) {
            oListener.onTopReached();
        } else {
            nListener.BottomNotReached();
        }*/

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

Solution

  • As Marteinn suggests:

     @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) { 
    
         if(view.getTop()==t){
            // reaches the top end
            }
    
        View view = (View) getChildAt(getChildCount()-1); 
        int diff = (view.getBottom()-(getHeight()+getScrollY()+view.getTop()));// Calculate the scrolldiff 
         if( diff <= 0 ){ 
            // if diff is zero, then the bottom has been reached
             Log.d(ScrollTest.LOG_TAG, "MyScrollView: Bottom has been reached" );
                 }
        super.onScrollChanged(l, t, oldl, oldt); 
    }