How to enable haptic feedback on button view

余生颓废 提交于 2019-11-28 17:28:09

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"></uses-permission>

I hope that helps.

A example to Mayra is, for run the Haptic Feedback is by use this code.

View view = findViewById(...)
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);

And this line of code can easy be include in you onclick action. The good part with this is you do not need to set a permission in the AndroidManifest ( I do not need this on SdkVersion "7" (2.1 or 2.3 is 7 ) )

Also do notes in my code here this will be run only if the use as enable Haptic Feedback as global. See http://developer.android.com/reference/android/view/HapticFeedbackConstants.html for alway use it.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!