Search code examples
androidhorizontalscrollview

How to disable HorizontalScrollView scrolling on button click and enable again on another button click?


I added a HorizontalScrollView in xml and I want to disable scrolling on button click and enable again on another button click.

Disabling scrolling with button click works but I don't know how to enable scrolling again.

The code below is how disabling scrolling worked.

class OnTouch implements View.OnTouchListener
{
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
}

I added the above class and then,

final HorizontalScrollView scrollView = (HorizontalScrollView)findViewById    (R.id.horizontalScrollView);
    Button stop = (Button)findViewById(R.id.stop);
    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            scrollView.setOnTouchListener(new OnTouch());
        }
    });

I added the above code inside onCreate method. I want to add another button(maybe "scroll") and I want that button to enable scrolling again.


Solution

  • How about this (I didn't test it, so there may be typos);

    class OnTouch implements View.OnTouchListener { 
        public boolean intercept = false;
        @Override public boolean onTouch(View v, MotionEvent event) { 
            return intercept; 
    } }
    
    final OnTouch listener = new OnTouch()); 
    final HorizontalScrollView scrollView = (HorizontalScrollView)findViewById (R.id.horizontalScrollView); 
    scrollView.setOnTouchListener(listener);
    Button stop = (Button)findViewById(R.id.stop);
    stop.setOnClickListener(new View.OnClickListener() { listener.intercept=true});
    Button start = (Button)findViewById(R.id.start);
    start.setOnClickListener(new View.OnClickListener() { listener.intercept=false});