Search code examples
androidandroid-buttonontouchlistenerandroid-scrollviewmotionevent

Android - Disable scrolling while holding button


I'v got a Button inside a ScrollView.

<ScrollView>
    <LinearLayout>
        ...
        <Button/>
        ...
    <LinearLayout/>
</ScrollView>

I'm using this button for recoding voice. When it catches MotionEvent.ACTION_DOWN event, I start recording, and on MotionEvent.ACTION_UP event I stop it.

buttomRecord.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            startRecording();
            return true;
        }
        else if(event.getAction() == MotionEvent.ACTION_UP){
            stopRecording();
            return true;
        }
        return false;
    }
});

The problem is when user is recording voice, if this ScrollView scrolls down or up, this button will loose focus and will never catch MotionEvent.ACTION_UP event.

How can I lock focus on Button while I'm holding it or disable ScrollView scrolling?


Solution

  • You can use

    mScrollView.requestDisallowInterceptTouchEvent(true);
    

    to disallow touch event of scrollview

    So your code will be

        buttomRecord.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                startRecording();
                mScrollView.requestDisallowInterceptTouchEvent(true);
                return true;
            }
            else if(event.getAction() == MotionEvent.ACTION_UP){
                stopRecording();
                mScrollView.requestDisallowInterceptTouchEvent(false);
                return true;
            }
            return false;
        }
    });