Bentley Carr
Bentley Carr

Reputation: 702

Android Development - OnTouchListener - How to Use?

I was wondering how one uses OnTouchListener. (I'm using Android Studio.)

This is my code and when I press the "Vibrate" button, the button image doesn't change to it's pressed state:

vibrateButton = (Button) findViewById(R.id.button_vibrate);
    vibrationInstance = (Vibrator) getSystemService(this.VIBRATOR_SERVICE);
    vibrateButtonPressed = false;
    if (!(vibrationInstance.hasVibrator())) {
        vibrateButton.setEnabled(false);
    }
    vibrateButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                vibrationInstance.cancel();
            }
            if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                vibrationInstance.vibrate(vibrationPattern, 0);
            }
            return false;
        }


    });

Is this how one uses OnTouchListener and what is the need for return false;? Thanks!

Upvotes: 1

Views: 2781

Answers (1)

Sipka
Sipka

Reputation: 2311

I guess your application is crashing because you forgot to add the permission to the manifest file. Make sure this is in it: <uses-permission android:name="android.permission.VIBRATE" />

And, by the way, if you want to receive all the touch events occuring to the View, you should return true in the OnTouchListener.

Upvotes: 1

Related Questions