Search code examples
androidandroid-scrollview

How to detect ScrollView scroll by desired pixel value


I'm extending ScrollView to detect if it was scrolled up or down. I want to add option to detect scroll only if it was scrolled by let's say 50 pixels. How to do that? My current code of scrollview overrides onScrollChanged:

public interface OnDetectScrollListener {
    void onUpScroll();
    void onDownScroll();
}

public class MyScrollView extends ScrollView {

    private OnDetectScrollListener onDetectScrollListener = null;
    private boolean scrollDown = false;
    private boolean scrollUp = false;

    .... constructors ....

    public void setOnDetectScrollListener(OnDetectScrollListener scrollViewListener) {
        this.onDetectScrollListener = scrollViewListener;
    }

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

            //scroll down
            if(t > oldt){
                if(!scrollDown & oldt >= 0 & t >= 0){
                    scrollDown = true;
                    scrollUp = false;
                    onDetectScrollListener.onDownScroll();
                }

            }
            //scroll up
            else if(t < oldt & diff > 0){
                if(!scrollUp){
                    scrollUp = true;
                    scrollDown = false;
                    onDetectScrollListener.onUpScroll();
                }
            }
        }
    }
}

Solution

  • I don't have much experience in ScrollView but you can do this:

    if what you want is to start scrolling only after 50 pixels you can follow this logic:

    bool scrolling = false;
    int scrollX = -1;
    int scrollY = -1;
    
    protected void scroll(int x, int y)
    {
        //View was not scrolling
        if (scrollX == -1)
        {
            //Save starting point
            scrollX = x;
        }
        //View keeps scrolling
        else
        {
            //User is touching 50 pixels left from starting point
            if (x -scrollX > 50)
            {
                scrolling = true;
            } else
            //User is touching 50 pixels right from starting point
            if (scrollX -x > 50)
            {
                scrolling = true;
            }
        }
    
        if (scrolling)
        {
            /* Your code */
        }
    }
    

    I'm not sure if either l or t is x or y on your onScrollView (I've never touched it) but you can implement it your way.

    Feel free to create separate variables for scrolling left and scrolling right (or up/down).

    Please avoid using pixels, especially for input. Prefer using density-independent pixels (dp). More info here (Supporting Multiple Screens.