Skip to content

Instantly share code, notes, and snippets.

@sonique6784
Last active June 22, 2023 21:28
Show Gist options
  • Save sonique6784/e310517c7aaae5da346868eab53daf33 to your computer and use it in GitHub Desktop.
Save sonique6784/e310517c7aaae5da346868eab53daf33 to your computer and use it in GitHub Desktop.
This show how to implements Indication and Hoverable on Compose. This is great to add Mouse and Stylus support in apps, such as hover state, focus state...
/* Copyright 2023 Google.
SPDX-License-Identifier: Apache-2.0 */
@Composable
fun hoverableHighlightAndPointer() {
val highlightIndication: Indication = remember {
HighlightIndication()
}
val interactionSource = MutableInteractionSource()
Column() {
// This allow to change the mouse cursor when the mouse is hovering the Text composable
// this is great if developers want to show an action is actionable on something that is not a button
Text(
"Hover me with mouse", modifier = Modifier
.pointerHoverIcon(icon = PointerIcon(TYPE_GRAB), false)
)
// This allow to change the background of the composable when mouse or stylus is hovering
// this is great when developers want to show what element of this UI is focused
Text(
"Hover me with mouse/stylus",
modifier = Modifier
.hoverable(interactionSource)
.indication(
interactionSource, highlightIndication
)
)
}
}
// this code can be found in AOSP androidx/foundation/compose/Indication.kt
// Indication
class HighlightIndication : Indication {
private class HighlightIndicationInstance(
private val isPressed: State<Boolean>,
private val isHovered: State<Boolean>,
private val isFocused: State<Boolean>,
) : IndicationInstance {
override fun ContentDrawScope.drawIndication() {
drawContent()
if (isPressed.value) {
drawRect(color = Color.Black.copy(alpha = 0.3f), size = size)
} else if (isHovered.value || isFocused.value) {
drawRect(color = Color.Black.copy(alpha = 0.1f), size = size)
}
}
}
@Composable
override fun rememberUpdatedInstance(interactionSource: InteractionSource): IndicationInstance {
val isPressed = interactionSource.collectIsPressedAsState()
val isHovered = interactionSource.collectIsHoveredAsState()
val isFocused = interactionSource.collectIsFocusedAsState()
return remember(interactionSource) {
HighlightIndicationInstance(isPressed, isHovered, isFocused)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment