Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Created August 17, 2023 16:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/59872ac111bdddbdb03cbca74c97b9f0 to your computer and use it in GitHub Desktop.
Save hrules6872/59872ac111bdddbdb03cbca74c97b9f0 to your computer and use it in GitHub Desktop.
Jetpack Compose Snackbar's swipe-to-dismiss behavior
/*
* Copyright (c) 2023. Héctor de Isidro - hrules6872
*
* 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