我想在整个应用程序上设置振动效果。我搜索代码,这是工作的onButtonClick,但我想当我设置为振动,然后振动效果应该设置为我的应用程序中的所有视图。所有按钮都应该振动吗?有没有办法在android中的任何视图上设置振动效果,或者我必须在所有视图上单独设置。以下是我现在使用的代码。
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();
}发布于 2021-08-23 08:00:30
我不明白你为什么要用这么复杂的方式做这件事。
更简单、更干净的解决方案是在xml文件android:hapticFeedbackEnabled="true"中启用触觉反馈。
编辑:这可以通过代码来完成。
注意,HapticFeedbackConstants类中的一些常量在某些版本的Android中可能是可用的,也可能是不可用的
public void onClick(View view) {
view.setHapticFeedbackEnabled(true);
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
//your other click logic here
}https://stackoverflow.com/questions/68888262
复制相似问题