Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about haptic feedback in Android

I have an Android app with 9 buttons. This app runs on 2.36 and is the only app on the device (or at least the only app we let the user use - we ship the device with our code preinstalled as part of a suite of industrial products we sell.)

All the buttons go to the same handler and get sorted out there by their tag. The handler is specified in the XML:

   <Button android:id="@+id/IdleButton"
     android:layout_marginLeft="5dp"
     android:background="@drawable/idle18pt_he_normal"
     android:hapticFeedbackEnabled="true"
     android:layout_width="92dp"
     android:layout_height="92dp"
     android:tag="0"
     android:onClick="theButtonHandler">
   </Button> 

I want to enable haptic feedback, i.e., a vibration, when the user presses the button. Is there a way to do this just in the XML, or if not, is there a way to do it in my onClick() handler?

The web examples I've seen (e.g., http://androidcookbook.com/Recipe.seam?recipeId=1242 ) for haptic feedback on Android mostly seem to involve changes to the manifest, changes to the XML (you can see I've already enabled it in my XML, above) and then declaring, initializing and implementing a separate Touch handler for the button. This seems like a lot of work, especially since I have 9 buttons.

Since I already have just one onClick handler for all my buttons is there a way I can implement the haptic feedback there?

All I had to do to get a "click" sound when I tap one of my buttons was to checkmark "Audible selection" in the "Sounds" part of the phone's settings - no coding at all. Why is haptic feedback so much more complicated?

like image 956
user316117 Avatar asked Sep 09 '14 15:09

user316117


1 Answers

Without using the VIBRATE permission.

You can use performHapticFeedback() function of any View including Button.

For example programmatically in Kotlin:

view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)

This vibrates the device.

You can vibrate the device from anywhere in your Fragment or Activity, even when you don't have a View available.

In Fragment you can do:

requireView().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)

In Activity you do:

window.decorView.rootView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
like image 87
Yogesh Umesh Vaity Avatar answered Sep 26 '22 13:09

Yogesh Umesh Vaity