UMBRELLAYour main purpose is to create consumer interface parts which might be extra interactive and assist customers take actions constantly, even when these actions have to be sped up or slowed down over time. To realize this, builders want to have the ability to observe how a lot time has handed since a consumer first faucets a compilation after which take the suitable motion based mostly on that data.
Our authentic modifier is onTouchHeld()pollDelay parameter to set the time window between every callback and a perform to name with the period of time elapsed for the reason that consumer held down their motion.
enjoyable Modifier.onTouchHeld(
pollDelay: Period,
onTouchHeld: (timeElapsed: Period) -> Unit
) = composed {
val scope = rememberCoroutineScope()
pointerInput(onTouchHeld) {
awaitEachGesture {
val initialDown = awaitFirstDown(requireUnconsumed = false)
val initialDownTime = System.nanoTime()
val initialTouchHeldJob = scope.launch {
whereas (initialDown.pressed) {
val timeElapsed = System.nanoTime() - initialDownTime
onTouchHeld(timeElapsed.nanoseconds)
delay(pollDelay)
}
}
waitForUpOrCancellation()
initialTouchHeldJob.cancel()
}
}
}
Shifting on to our subsequent Modifier is onTouchHeldAnimated()this time our Modifier has further parameters that mean you can enhance or lower the polling delay for a sure time and even assist numerous easing capabilities immediately.
enjoyable Modifier.onTouchHeldAnimated(
easing: Easing = FastOutSlowInEasing,
pollDelay: Period = 500.milliseconds,
targetPollDelay: Period = pollDelay,
animationDuration: Period = 5.seconds,
onTouchHeld: () -> Unit
) = composed {
val scope = rememberCoroutineScope()
pointerInput(onTouchHeld) {
val animationSpec: FloatAnimationSpec = FloatTweenSpec(
animationDuration.inWholeMilliseconds.toInt(),
0,
easing
)
awaitEachGesture {
val initialDown = awaitFirstDown(requireUnconsumed = false)
val initialTouchHeldJob = scope.launch {
var currentPlayTime = 0.milliseconds
var delay = pollDelay
whereas (initialDown.pressed) {
onTouchHeld()
delay(delay.inWholeMilliseconds)
currentPlayTime += delay
delay = animationSpec.getValueFromNanos(
currentPlayTime.inWholeNanoseconds,
pollDelay.inWholeMilliseconds.toFloat(),
targetPollDelay.inWholeMilliseconds.toFloat(),
0F
).toInt().milliseconds
}
}
waitForUpOrCancellation()
initialTouchHeldJob.cancel()
}
}
}
To realize an acceleration counter over time, as demonstrated in our instance, you possibly can set the targetPollDelay decrease. This may progressively cut back the delay between every callback over time, leading to a quick increment of the counter in case you increment it on every callback. This method may help create dynamic and interesting consumer experiences.
Combining new modifiers like onTouchHeld() and onTouchHeldAnimated() may help you create dynamic consumer experiences in Jetpack Compose. Strive it out and see how they will take your Compose Powered UI to the subsequent degree!