我想在 kotlin 中使用惰性列创建卷轴功能,用户可以一次滚动单个项目,而不是多个项目。
我尝试使用
flingBehavior = rememberSnapFlingBehavior(
snapLayoutInfoProvider = SnapLayoutInfoProvider(state)
)
此代码可以捕捉项目,但无法阻止用户一次滚动多个项目 我尝试使用分页器,但分页器性能不如惰性列。
最佳答案
实际上寻呼机的目的就是做这样的事情,它提供了更多可以使用的功能,而且高效且易于实现。但如果您仍然想对 LazyColumn 执行相同的操作,那么我们必须实现自己的滚动行为。并且,您可以按照以下简单步骤来完成此操作:
第 1 步:将 userScrollEnabled
设置为 false
,以便用户无法执行默认滚动。
第 2 步:使用 rememberLazyListState
将 state
传递给 LazyColumn
,方法是将其保存在不同的变量中,就像我们一样稍后会用到。
第 3 步:现在按照代码所示设置拖动手势的修饰符
,然后您就可以尝试该功能了。
val lazyListState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
var currentIndex = 0
var job: Job? = null
LazyColumn(
state = lazyListState,
userScrollEnabled = false, // to restrict the default scrolling behaviour
modifier = Modifier
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consume()
val (x,y) = dragAmount
// cancelling the previous job
job?.cancel()
job = coroutineScope.launch{
// Waiting for next gesture changes
delay(100)
// Although we don't need right and left swipes
when {
x > 0 -> { /* swiped right */ }
x < 0 -> { /* swiped left */ }
}
when {
y > 0 -> { /* swiped down */
try { lazyListState.animateScrollToItem(--currentIndex) }
catch (e: Exception) { /* handle the error */}
}
y < 0 -> { /* swiped up */
try { lazyListState.animateScrollToItem(++currentIndex) }
catch (e: Exception) { /* handle the error */}
}
}
}
}
}
) {
// List content...
}
注意:在此逻辑中,currentIndex
可以超出限制,但应用程序不会崩溃,因此您还可以处理这些边缘情况。
您可能会问我们为什么要进行工作分配和取消。所以原因是手势快速变化多次,因此它可以进行多次滚动,因此为了解决这个问题,我们使用了防抖技术。您可以在我的解决方案之一中查看更多信息:https://stackoverflow.com/a/76968173/14972910
关于android - 如何实现惰性列一次滚动一列的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77020828/