Skip to content

Instantly share code, notes, and snippets.

@aabadaa
Created October 26, 2023 07:36
Show Gist options
  • Save aabadaa/bfab1cc2c7e20070c3053b6cd2783ea7 to your computer and use it in GitHub Desktop.
Save aabadaa/bfab1cc2c7e20070c3053b6cd2783ea7 to your computer and use it in GitHub Desktop.
This composable enables you to create swipable cards or any other content easily , I created it because the material3 SwipeToDissmiss is throwing exception in this time
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntOffset
import kotlin.math.abs
import kotlin.math.roundToInt
enum class Direction {
Left, Right
}
@Composable
fun Swipable(
modifier: Modifier = Modifier,
onSwipe: (Direction) -> Unit,
ratio: Float = .5f,
background: @Composable RowScope.() -> Unit = {},
content: @Composable RowScope.() -> Unit,
) {
var xOffset by remember { mutableIntStateOf(0) }
val animatedOffset by animateIntAsState(targetValue = xOffset, label = "animated offset")
var width by remember { mutableFloatStateOf(0f) }
Box(
modifier
.onSizeChanged { width = it.width.toFloat() }
.pointerInput(Unit) {
detectHorizontalDragGestures(
onDragEnd = {
if (!width.isNaN() && width > 0)
if (abs(xOffset / width) >= ratio)
if (xOffset < 0)
onSwipe(Direction.Left)
else if (xOffset > 0)
onSwipe(Direction.Right)
xOffset = 0
}
) { _, dragAmount ->
xOffset += dragAmount.roundToInt()
}
}
) {
Row(
content = background,
modifier = Modifier.matchParentSize()
)
Row(
content = content,
modifier = Modifier.offset { IntOffset(animatedOffset, 0) }
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment