Custom View: Swipe Button in Compose

Barros
3 min readJul 10, 2022

--

Photo by Guido Coppa on Unsplash

In this article I’ll explain how to create a swipe button that it launches a callback when it swiped.

We created a composable function called SwipeButton and added some style parameters, the text message, the icon to swipe and the onSwipe callback.

We defined a swipeableState to remember the state of the swiping and we added an animateFloatAsState to let the text disappear when is swiping.

We used the state with Side Effects. When the animation is running, we created aDisposableEffect and when the animation is finished, onDispose is called. We used a 0 for the initialValue and 1 for the endValue, so onSwipeis called on the endValue.

We defined the iconSize to update it dinamically and obtain the maxWidth to know where the icon should stop at the endValue. It takes all the boxWithConstraints.maxWidth less the iconSize.width.

In the inner level we use onGloballyPositioned to update the iconSize value and to recompose and obtain the correct value. Also, we defined the anchors (0 to the initialValue and the maxWidth to the endValue). With the FractionalThreshold we define the threshold where the icon reach the endValue in this case it doesn’t change state at least it reaches the 90% of the width.

The complete SwipeButton looks like:

You can find more on swiping in Compose here.

In the following repository, you can find the completed runnable implementation:

You can find a branch with the implementation of Material 3. But right now, there isn’t a way to use swipeable with Material 3, so there are both the libraries.

Thank you, I hope you enjoyed reading it.

--

--

No responses yet