简体   繁体   中英

vibrate on click of every view in android

I want to set vibration effect on whole app. I search code and this is working onButtonClick but i want when i set to vibration on then vibration effect should be set to all views in my app. All Buttons should vibrate? Is there any way to set vibration effect on any views in android or i have to set on all views separately. Following is the code that i am using now.

vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  sw_vibration.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    editor.putBoolean(getString(R.string.vibration), true);
                    startVibrate();
                } else {
                    editor.putBoolean(getString(R.string.vibration), false);
                    stopVibrate();
                }
                editor.commit();
            }
        });

 public void startVibrate() {

        final VibrationEffect vibrationEffect;

        // this is the only type of the vibration which requires system version Oreo (API 26)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            // this effect creates the vibration of default amplitude for 1000ms(1 sec)
            vibrationEffect = VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE);
            
            vibrator.vibrate(vibrationEffect);
        }
    }
  public void stopVibrate() {
        vibrator.cancel();
    }


I don't see why you are doing it in such a complicated way.

A simpler and cleaner solution would be to enable haptic feedback in the xml file android:hapticFeedbackEnabled="true"

EDIT: This could be done via code as so

Note that, few of the constants in HapticFeedbackConstants class may or may not be available for certain versions of Android

public void onClick(View view) {
 view.setHapticFeedbackEnabled(true);
 view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
       //your other click logic here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM