Last active
November 29, 2024 12:19
-
-
Save hector6872/59872ac111bdddbdb03cbca74c97b9f0 to your computer and use it in GitHub Desktop.
Jetpack Compose Snackbar's swipe-to-dismiss behavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2023. Héctor de Isidro - hector6872 | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
enum class SwipeDirection { | |
START, | |
IDLE, | |
END, | |
} | |
@OptIn(ExperimentalMaterialApi::class) | |
@Composable | |
fun SwipeableSnackbarHost(hostState: SnackbarHostState) { | |
if (hostState.currentSnackbarData == null) return | |
val swipeableState = rememberSwipeableState(IDLE) | |
var size by remember { mutableStateOf(Size.Zero) } | |
val width = remember(size) { if (size.width == 0f) 1f else size.width } | |
if (swipeableState.isAnimationRunning) { | |
DisposableEffect(swipeableState) { | |
onDispose { | |
when (swipeableState.currentValue) { | |
START, | |
END -> hostState.currentSnackbarData?.dismiss() | |
else -> return@onDispose | |
} | |
} | |
} | |
} | |
SnackbarHost( | |
hostState, | |
modifier = Modifier | |
.onSizeChanged { size = Size(it.width.toFloat(), it.height.toFloat()) } | |
.swipeable( | |
state = swipeableState, | |
anchors = mapOf( | |
-width to START, | |
0f to IDLE, | |
width to END, | |
), | |
orientation = Horizontal | |
), | |
snackbar = { snackbarData -> | |
Snackbar( | |
snackbarData, | |
modifier = Modifier.offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) } | |
) | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment