先说我发现的一个问题,当手指停止滑动但还留在屏幕上时,Lazy List默认没有Fling行为,而Lazy Grid是默认有Fling行为的。
所以我们在NestedScroll中嵌套LazyList和LazyGrid并发生滑动行为时,屏幕的表现是有所区别的,所以在写Nested Connection时,要注意onPreFling方法的使用,在嵌套List时,手指静止离开屏幕并不会调用onPreFling,而在嵌套Grid时,手指静止离开屏幕则依然会调用onProFling。
顺便分享一下我编写的滑动隐藏Appbar的NestedScrollConnection的代码,注释掉的部分在嵌套List时需要恢复,不然无法实现吸附效果
val gridNestedScrollConnection = remember {
object : NestedScrollConnection {
var dragCount = 0f
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
dragCount += available.y
var consume = available.y;
if (dragCount <= -appBarHeightPx) {
dragCount = (-appBarHeightPx)
consume = 0f
}
if (dragCount >= 0) {
dragCount = 0f
consume = 0f
}
scope.launch {
heightOffset.snapTo(dragCount)
}
return Offset(x = 0f, y = consume)
}
var flingCount = 0f
override suspend fun onPreFling(available: Velocity): Velocity {
// if (available.y == 0f) {
// if (heightOffset.value < -appBarHeightPx / 2) {
// heightOffset.animateTo(-appBarHeightPx)
// } else {
// heightOffset.animateTo(0f)
// }
// return Velocity.Zero
// }
flingCount += available.y
var consume = available.y
if (flingCount + heightOffset.value <= -appBarHeightPx) {
flingCount = 0f
consume = 0f
}
if (flingCount + heightOffset.value >= 0) {
flingCount = 0f
consume = 0f
}
scope.launch {
heightOffset.snapTo(flingCount + heightOffset.value)
}
return Velocity(x = 0f, y = consume)
}
override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
if (heightOffset.value < -appBarHeightPx / 2) {
heightOffset.animateTo(-appBarHeightPx)
} else {
heightOffset.animateTo(0f)
}
return Velocity.Zero
}
}
}