首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在android中点击每一个视图都会震动

在android中点击每一个视图都会震动
EN

Stack Overflow用户
提问于 2021-08-23 06:40:47
回答 1查看 108关注 0票数 0

我想在整个应用程序上设置振动效果。我搜索代码,这是工作的onButtonClick,但我想当我设置为振动,然后振动效果应该设置为我的应用程序中的所有视图。所有按钮都应该振动吗?有没有办法在android中的任何视图上设置振动效果,或者我必须在所有视图上单独设置。以下是我现在使用的代码。

代码语言:javascript
复制
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();
    }
EN

回答 1

Stack Overflow用户

发布于 2021-08-23 08:00:30

我不明白你为什么要用这么复杂的方式做这件事。

更简单、更干净的解决方案是在xml文件android:hapticFeedbackEnabled="true"中启用触觉反馈。

编辑:这可以通过代码来完成。

注意,HapticFeedbackConstants类中的一些常量在某些版本的Android中可能是可用的,也可能是不可用的

代码语言:javascript
复制
public void onClick(View view) {
 view.setHapticFeedbackEnabled(true);
 view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
       //your other click logic here
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68888262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档