Reputation: 31
I want to monitor the whole screen and detect if swipe gestures occur.
How can I do this in one function? Easy short and readable would be great.
Would be nice if you explain the steps so I better understand what needs to be done for this.
Upvotes: 0
Views: 668
Reputation: 298
You can use Modifier.swipeable
of WearMaterialApi on your top level container :
val swipeState = SwipeableState<String>("initial")
val anchors = mapOf(0f to "left", 1f to "right")
Column(
modifier = Modifier.swipeable(
state = swipeState,
anchors = anchors,
orientation = Orientation.HORIZONTAL,
enabled = true,
reverseDirection = false,
interactionSource = null,
thresholds = { _, _ ->
FractionalThreshold(0.5f) },
resistance = resistanceConfig(anchors.keys),
velocityThreshold = Dp(200)
)
) {
Text(swipeState.value)
}
It let you define a map of anchors that represent the bounds of the swipe options.
You can make your UI logic around the value of swipstate
In the exemple the text will show right if right swipe occured and left if left swipe occured.
If you want to detect vertical and horizontal swipes at the same times you can use two Modifier.swipeable
on a single composable by using Modifier.then
like that :
val horizontalSwipeState =
SwipeableState<String>("initial")
val horizontalAnchors = mapOf(0f to "left",
1f to "right")
val verticalSwipeState = SwipeableState<String>("initial")
val verticalAnchors = mapOf(0f to "up", 1f to "down")
Box(
modifier = Modifier
.swipeable(
state = horizontalSwipeState,
anchors = horizontalAnchors,
orientation = Orientation.HORIZONTAL,
enabled = true,
reverseDirection = false,
interactionSource = null,
thresholds = { _, _ -> FractionalThreshold(0.5f) },
resistance = resistanceConfig(horizontalAnchors.keys),
velocityThreshold = Dp(200)
)
.then(
Modifier.swipeable(
state = verticalSwipeState,
anchors = verticalAnchors,
orientation = Orientation.VERTICAL,
enabled = true,
reverseDirection = false,
interactionSource = null,
thresholds = { _, _ -> FractionalThreshold(0.5f) },
resistance = resistanceConfig(verticalAnchors.keys),
velocityThreshold = Dp(200)
)
)
) {
Text("Horizontal:
${horizontalSwipeState.value} Vertical:
${verticalSwipeState.value}")
}
And use a different threshold for each orientation to avoid the two swipes overlaping each others
Upvotes: 0