Android button onLongClick, how to get the listener when the button is released from a long click [duplicate]

StackOverflow https://stackoverflow.com//questions/21047773

Question

I'm following this tutorial to implement a recorder in Android, which contains the code below, when the button is held, start recording, when released, stop recording, but I can't find the listener when the button is released, any advice? Thank you in advance

button.setOnLongClickListener(new View.OnLongClickListener() {          
        @Override
        public boolean onLongClick(View arg0) {
            startRecording();
            return false;
        }           
    });

private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(voiceFileName);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }
    mRecorder.start();
}

private void stopRecording() {
    mRecorder.stop();
    mRecorder.release();
    mRecorder = null;
}
Was it helpful?

Solution

You shouldn't implement the longclicklistener, you should implement the OnTouchListener.

There you will have the touch event, and do this:

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){

            stopRecording();
            return true;
        }else{
            startRecording();
            return true;
        }
        return false;
    }
});

OTHER TIPS

the boolean value "start" controls it

 private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

and then

 class RecordButton extends Button {
        boolean mStartRecording = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onRecord(mStartRecording);
                if (mStartRecording) {
                    setText("Stop recording");
                } else {
                    setText("Start recording");
                }
                mStartRecording = !mStartRecording;
            }
        };

controls it

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top