androidvibration

How to enable haptic feedback on button view


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?


Solution

  • Here is an answer, though it might not be the best implementation:

    import android.view.View;
    import android.os.Vibrator;
    
    public class Main extends Activity implements OnClickListener
    {
        private View myView;
        private Vibrator myVib;
    
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
    
            //myView can be any type of view, button, etc.
            myView = (View) this.findViewById(R.id.myView);
            myView.setOnClickListener(this);
        }
        
        @Override
        public void onClick(View v)
        {
            myVib.vibrate(50);
            //add whatever you want after this
        }
    }
    

    Don't forget, you also need to add the "android.permission.VIBRATE" permission to the program's manifest. You can do so by adding the following to the "AndroidManifest.xml" file:

    <uses-permission android:name="android.permission.VIBRATE"/>