-
Notifications
You must be signed in to change notification settings - Fork 292
Open
Description
// [START android_compose_components_iconbutton]
@composable
fun MomentaryIconButton(
unselectedImage: Int,
selectedImage: Int,
contentDescription: String,
modifier: Modifier = Modifier,
stepDelay: Long = 100L, // Minimum value is 1L milliseconds.
onClick: () -> Unit
) {
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val pressedListener by rememberUpdatedState(onClick)
LaunchedEffect(isPressed) {
while (isPressed) {
delay(stepDelay.coerceIn(1L, Long.MAX_VALUE))
pressedListener()
}
}
IconButton(
modifier = modifier,
onClick = onClick,
interactionSource = interactionSource
) {
Icon(
painter = if (isPressed) painterResource(id = selectedImage) else painterResource(id = unselectedImage),
contentDescription = contentDescription,
)
}
}
// [END android_compose_components_iconbutton]
// [START android_compose_components_momentaryiconbuttons]
@Preview()
@composable
fun MomentaryIconButtonExample() {
var pressedCount by remember { mutableIntStateOf(0) }
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
MomentaryIconButton(
unselectedImage = R.drawable.fast_rewind,
selectedImage = R.drawable.fast_rewind_filled,
stepDelay = 100L,
onClick = { pressedCount -= 1 },
contentDescription = "Decrease count button"
)
Spacer(modifier = Modifier)
Text("advanced by $pressedCount frames")
Spacer(modifier = Modifier)
MomentaryIconButton(
unselectedImage = R.drawable.fast_forward,
selectedImage = R.drawable.fast_forward_filled,
contentDescription = "Increase count button",
stepDelay = 100L,
onClick = { pressedCount += 1 }
)
}
}
// [END android_compose_components_momentaryiconbuttons]
Metadata
Metadata
Assignees
Labels
No labels