Search code examples
androidonclickontouch

Click and press-release on same button


I implemented my own camera to capture image and video. I want to perform two actions on the same button.

  1. When the button is clicked I want to execute code for image capture.
  2. When I continuously press the button I want to start recording and when I release the button I want to stop recording.

Suppose I have 3 methods for above task namely captureImage(), startVideo() and stopVideo().

How to implement the above two actions on the same button? When should I call above three methods?

I tried using onClick, ACTION_DOWN and ACTION_UP, however, in this case onClick never gets called. Always ACTION_DOWN and ACTION_UP gets called.


Solution

  • This is how I solved it. On ACTION_DOWN start video recording after 1 second. On ACTION_UP check if you are capturing video then stop capturing otherwise capture image and cancel video capture handler.

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            isImage = false;
            startRecording();
        }
    };
    
    
    mCaptureButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // Start recording after 1 sec
                        isImage = true;
                        mHandler = new Handler();
                        mHandler.postDelayed(mRunnable, 1000);
                        break;
                    case MotionEvent.ACTION_UP:
                        // If video recording was started after 1 sec delay then stop recording
                        // otherwise capture image
                        if(isImage) {
                            // Cancel handler for video recording
                            mHandler.removeCallbacks(mRunnable);
                            // Capture image
                            mCamera.takePicture(null, null, mPicture);
                        } else {
                            // Stop video recording
                            stopRecording();
    
                        }
                        break;
                }
                return true;
            }
        });