我正在尝试添加滑动以关闭到 LazyList。
SwipeToDismiss 的默认实现将导致在尝试垂直滚动时意外水平滚动,从而导致意外滑动以关闭事件。
在原生 Android 视图世界中,我会设置一个触摸监听器,并在开始滑动以关闭之前检查 x > y 触摸事件距离。但是在 Jetpack Compose 中我不知道如何操作。
我尝试了pointerInput修饰符,但是它完全禁用了垂直滚动。
我知道解雇阈值,但这只能处理调用解雇状态更改。
@Composable
fun MyList(modifier: Modifier = Modifier, list: MutableState<List<String>>) {
val scrollState: LazyListState = rememberLazyListState()
LazyColumn(
modifier = modifier
.fillMaxWidth()
.background(MaterialTheme.colors.surface),
state = scrollState,
) {
items(
items = list.value,
key = { it },
contentType = { 0 }
) { item ->
MySwipeToDismiss(modifier = modifier, onSwipeLeft = {}, onSwipeRight = {}) {
Text(text = item)
}
}
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MySwipeToDismiss(modifier: Modifier = Modifier, onSwipeLeft: () -> Unit, onSwipeRight: () -> Unit, content: @Composable () -> Unit) {
val dismissState = rememberDismissState {
when (it) {
DismissValue.Default -> return@rememberDismissState false
DismissValue.DismissedToEnd -> onSwipeRight()
DismissValue.DismissedToStart -> onSwipeLeft()
}
true
}
SwipeToDismiss(
modifier = modifier,
state = dismissState,
dismissThresholds = { FractionalThreshold(0.7f) },
background = {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
)
}
) {
content()
}
}
任何建议都将受到高度赞赏。
我浪费了很多时间试图找到解决方案来解决这个问题,最后用这个解决了它。这几乎可以完美地防止意外滑动。
val current = LocalViewConfiguration.current
CompositionLocalProvider(LocalViewConfiguration provides object : ViewConfiguration by current{
override val touchSlop: Float
get() = current.touchSlop * 5f
}) {
// Wrap your row composable inside this
}
此解决方案是由 Google 开发人员在问题线程中建议的。