kotlinandroid-jetpack-composewear-os

Current mechanism to detect a fling gesture on Wear OS with Jetpack Compose


I am trying to detect a fling gesture on Wear OS. Documentation on https://developer.android.com/jetpack/compose/touch-input/pointer-input/drag-swipe-fling states that

Note: The swipeable APIs have been replaced by Foundation's anchoredDraggable APIs in Jetpack Compose 1.6.0-alpha01. Read more in the migration guide.

I have yet to find an example for anchoredDraggable that works. Seems like anchoredDraggable is still a work in progress. What is the correct, current, not-deprecated method of detecting a fling up gesture with Jetpack Compose on Wear OS?


Solution

  • Based on the official documentation (that you reference in your question), AnchoredDraggable is the preferred way to support certain swipe and fling behavior on a UI component.

    You're correct in that the same documentation doesn't actually show an example of how to implement support for the fling gesture...

    I learned about fling from this video. The two sections starting at the timestamp in the link shows how to build everything from scratch. The following section shows how to use an AnchoredDraggable to achieve the same effect. Depending on what exactly you are trying to do, you might want/have to do the gesture detection yourself, in which case your code is going to end up looking something like this:

    val translationX = remember {
        Animatable(0f)
    }
    
    val decay = rememberSplineBasedDecay<Float>()
    
    ComposableToFling(
        modifier = Modifier
          .draggable(draggableState, Orientation.Horizontal,
            onDragStopped = { velocity ->
                val decayX = decay.calculateTargetValue(
                    translationX.value,
                    velocity
                )
                coroutineScope.launch {
                    // Do something with the fling gesture
                }
            }
          )
    )
    

    Please note that I've deliberately omitted code in the snippet above in an attempt to highlight the fling gesture detection. You will need to add a couple of additional pieces (all in the video) for this to compile and run.