Zoltan Demant
02/09/2022, 4:59 AMrememberDraggableState
and vibrating after a certain drag distance, I often see the vibration not staying in sync with the drag events. Is this a bug? Code in thread 🧵inline fun Modifier.draggable(
minimumOffset: Dp = 30.dp,
crossinline onDragged: (DragDirection) -> Unit
): Modifier {
return composed {
val vibrator = rememberVibrator()
var offset = remember { 0f }
val minimumOffsetPx = with(LocalDensity.current) {
minimumOffset.toPx()
}
draggable(
orientation = Vertical,
onDragStopped = {
offset = 0f
},
state = rememberDraggableState { delta ->
offset += delta
if (offset.absoluteValue >= minimumOffsetPx) {
offset = 0f
val direction = when {
delta <= 0 -> Up
else -> Down
}
onDragged(direction)
vibrator.vibrate(Light)
}
}
)
}
}
enum class DragDirection {
Up,
Down;
}
vibrator.vibrate() leads to this
val effect = VibrationEffect.createOneShot(
vibration.length(),
DEFAULT_AMPLITUDE
)
vibrator.vibrate(effect)
Albert Chang
02/09/2022, 9:59 AMvar offset by remember { mutableStateOf(0f) }
.Zoltan Demant
02/09/2022, 10:07 AMAlbert Chang
02/09/2022, 10:23 AMremember
in your code is pointless and offset
will be reset to 0 on every recomposition.
You don't necessarily need a mutable state but you definitely need a value holder.Zoltan Demant
02/09/2022, 10:34 AMmutableStateOf
👍🏽 The pure logic of the Modifier
works flawlessly, e.g. the drag Up/Down
is invoked accordingly, but the vibration effect is not.