在我的手机(以及我测试过的其他设备)上,手机既不振动LongPress
也不TextHandleMove
振动。
在我们像这样迁移到 Compose 之前,我们已经解决了这个问题:
import android.content.Context
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.accessibility.AccessibilityManager
fun View.vibrate() = reallyPerformHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
fun View.vibrateStrong() = reallyPerformHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
private fun View.reallyPerformHapticFeedback(feedbackConstant: Int) {
if (context.isTouchExplorationEnabled()) {
// Don't mess with a blind person's vibrations
return
}
// Either this needs to be set to true, or android:hapticFeedbackEnabled="true" needs to be set in XML
isHapticFeedbackEnabled = true
// Most of the constants are off by default: for example, clicking on a button doesn't cause the phone to vibrate anymore
// if we still want to access this vibration, we'll have to ignore the global settings on that.
performHapticFeedback(feedbackConstant, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING)
}
private fun Context.isTouchExplorationEnabled(): Boolean {
// can be null during unit tests
val accessibilityManager = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager?
return accessibilityManager?.isTouchExplorationEnabled ?: false
}
现在,我们仍然必须使用此代码并从 Compose 访问它,就像Daniele Segato 的回答一样:
@Composable
fun VibratingButton() {
val view = LocalView.current
Button(onClick = {
view.vibrate()
}) { ... }
}