rememberLazyListState 是 Jetpack Compose 中用于控制 LazyColumn 或 LazyRow 滚动行为的一个状态管理工具
val horizonListState = rememberLazyListState()
LazyRow(
state = listState,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
reverseLayout = true
)
。。。。。。
通过 LazyListState我们可以:
1.控制列表滚动
例如下面,当用户点击选项触发 selectedIndex 变化之后,可以通过如下代码,将列表滚动到 当前选中的item
LaunchedEffect(selectedIndex) {
LogUtils.d("LaunchedEffect 当前选中项 selectedIndex=$selectedIndex,")
val center = horizonListState.layoutInfo.viewportEndOffset / 2
val selectedItem = horizonListState.layoutInfo.visibleItemsInfo.getOrNull(selectedIndex + 1)
selectedItem?.let {
horizonListState.scrollToItem(selectedIndex + 1, -center + it.size / 2)
}
}
2 监听滚动位置,触发自动加载
// 横向列表统计数据无限加载检测
LaunchedEffect(horizonListState, currentStatistics) {
snapshotFlow { horizonListState.layoutInfo }.collect { layoutInfo ->
//自动加载
if (layoutInfo.visibleItemsInfo.isNotEmpty() && !currentStatistics.isNullOrEmpty() && layoutInfo.visibleItemsInfo.last().index >= currentStatistics!!.size - 3) {
loadMoreStatistic(viewModel, viewType)
}
}
}