Skip to content

Instantly share code, notes, and snippets.

@carterhudson
Last active September 7, 2021 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carterhudson/a24086048201f5baf3f791bdd89017a1 to your computer and use it in GitHub Desktop.
Save carterhudson/a24086048201f5baf3f791bdd89017a1 to your computer and use it in GitHub Desktop.
@Composable
fun RepeatingButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
enabled: Boolean = true,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
elevation: ButtonElevation? = ButtonDefaults.elevation(),
shape: Shape = MaterialTheme.shapes.small,
border: BorderStroke? = null,
colors: ButtonColors = ButtonDefaults.buttonColors(),
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
maxDelayMillis: Long = 1000,
minDelayMillis: Long = 5,
delayDecayFactor: Float = .20f,
content: @Composable RowScope.() -> Unit
) {
Button(
modifier = modifier.repeatingClickable(
interactionSource = interactionSource,
enabled = enabled,
maxDelayMillis = maxDelayMillis,
minDelayMillis = minDelayMillis,
decayFactor = delayDecayFactor
) { onClick() },
onClick = {},
enabled = enabled,
interactionSource = interactionSource,
elevation = elevation,
shape = shape,
border = border,
colors = colors,
contentPadding = contentPadding,
content = content
)
}
fun Modifier.repeatingClickable(
interactionSource: InteractionSource,
enabled: Boolean,
maxDelayMillis: Long = 1000,
minDelayMillis: Long = 5,
delayDecayFactor: Float = .20f,
onClick: () -> Unit
): Modifier = composed {
val currentClickListener by rememberUpdatedState(onClick)
pointerInput(interactionSource, enabled) {
forEachGesture {
coroutineScope {
awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false)
val heldButtonJob = launch {
var currentDelayMillis = maxDelayMillis
while (enabled && down.pressed) {
currentClickListener()
delay(currentDelayMillis)
val nextMillis = currentDelayMillis - (currentDelayMillis * delayDecayFactor)
currentDelayMillis = nextMillis.toLong().coerceAtLeast(minDelayMillis)
}
}
waitForUpOrCancellation()
heldButtonJob.cancel()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment