How to enable haptic feedback on button view

Viewed 66540

I want to add haptic feedback to my application's buttons and control them programmatically to show button state (enabled and disabled). The default haptic feedback setter works only for long press. How can i make it work for simple button clicks.

And is there a way to have haptic feedback on events like touch move?

6 Answers

View has a performHapticFeedback function, which should allow you to perform it whenever you want, i.e., on an OnClick listener.

getWindow().getDecorView().performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);

a straightforward approach you can use in an activity.

In addition to the previous answers please make sure that "Vibration Feedback" option is enabled from your device settings

In my case I was trying to preform haptic feedback when a dialog fragment opened. The existing answers to this question weren't working. I had to wrap in postDelayed to get it to work.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    preformHapticFeedback()
}

private fun preformHapticFeedback() {
    val delay = 1L
    requireView().postDelayed(
        {
            requireView().performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
        },
        delay
    )
}
Related