Mick Byrne
Mick Byrne

Reputation: 14484

Disable Android scrollview, but still allow taps on buttons in the scroll view

I want to be able to prevent a user from being able to scroll in my Android ScrollView, but still detect when they tap a button that is within the scroll view.

I've subclassed the ScrollView class and have been fiddling around with the onInterceptTouchEvent and onTouchEvent methods, but can't seem to get it quite right. The code below stops the scrolling, but seems to disable tap (but not all, like if you go up and down without any move it works, but if your finger moves slightly as you tap it doesn't register). I've also just removed the onInterceptTouchEvent as well which almost works, but the scrollview still scrolls as the user removes their finger.

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        App.log("onInterceptTouchEvent, with action : " + ev.getAction());
        switch(ev.getAction())
        {
            case MotionEvent.ACTION_MOVE:
                return true;
        }
        return super.onInterceptTouchEvent(ev);

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        App.log("onTouchEvent, with action : " + ev.getAction());
        switch(ev.getAction())
        {
            case MotionEvent.ACTION_MOVE:
                return false;
        }
        return super.onTouchEvent(ev);
    }

Upvotes: 1

Views: 1699

Answers (2)

Mick Byrne
Mick Byrne

Reputation: 14484

In the end, I found the following solution did exactly what I needed:

@Override
public boolean onTouchEvent(MotionEvent ev)
{
    App.log("onTouchEvent, with action : " + ev.getAction());
    switch(ev.getAction())
    {
        case MotionEvent.ACTION_MOVE:
            return false;
    }
    return super.onTouchEvent(ev);
}

Upvotes: 2

nmw
nmw

Reputation: 6754

You can override overscrollBy() and change the deltaX & deltaY values to 0 if disabled.

@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
{
    final int dx;
    final int dy;

    if (isEnabled())
    {
        dx = deltaX;
        dy = deltaY;
    }
    else
    {
        dx = 0;
        dy = 0;
    }

    return super.overScrollBy(dx, dy, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
}

You'll probably also want to dynamically hide/show the scroll bar too on disabling/enabling.

Upvotes: 1

Related Questions