Android 如何在触摸应用程序中的每个按钮时启用振动

Android 如何在触摸应用程序中的每个按钮时启用振动,android,kotlin,vibration,Android,Kotlin,Vibration,在我的设置菜单中,当我打开开关时,我希望应用程序中的每个按钮都振动,当我关闭开关时,我希望应用程序中的每个按钮都不振动 以下是我迄今为止尝试过的代码 switch2!!.setOnCheckedChangeListener { buttonView, isChecked -> if (switch2!!.isChecked) { switch2!!.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);

在我的设置菜单中,当我打开开关时,我希望应用程序中的每个按钮都振动,当我关闭开关时,我希望应用程序中的每个按钮都不振动

以下是我迄今为止尝试过的代码

    switch2!!.setOnCheckedChangeListener { buttonView, isChecked ->
        if (switch2!!.isChecked) {
switch2!!.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        }
        else {
                vibrator.cancel()
            }
        }
你可以这样做

  • 使用
    SharedReference

  • 存储密钥后,可以在其他活动/片段中使用该密钥

  • onCreate
    ,您可以从
    SharedReference
    获取值

  • 在单击按钮之前,首先使用变量检查它

  • 如果是,则振动它。参考这个

  • **不要忘记在
    AndroidManifest
    中声明,如上所述

    <uses-permission android:name="android.permission.VIBRATE" />
    
    然后在
    内单击
    按钮

        if (isVisible) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
            } else {
                vibrator.vibrate(200)
            }
        }
    

    您需要先添加此权限

    <uses-permission android:name="android.permission.VIBRATE"/>
    
    <uses-permission android:name="android.permission.VIBRATE"/>
    
    fun vibratePhone(context: Context?, milliseconds: Int) {
        val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        if (Build.VERSION.SDK_INT >= 26) {
            vibrator.vibrate(
                VibrationEffect.createOneShot(
                    milliseconds,
                    VibrationEffect.DEFAULT_AMPLITUDE
                )
            )
        } else {
            vibrator.vibrate(milliseconds)
        }
    }