这个问题是由于LazyVerticalGrid/Column的行为不像我们期望的那样工作,有时候会出现行的重叠或不对齐的情况。为了解决这个问题,需要使用NestedScroll来正确地调整视图。
示例代码:
@Composable fun MyScreen() { Box (modifier = Modifier.fillMaxSize()) { val scrollState = rememberLazyListState() LazyColumn(state = scrollState) { items(100) { // Your logical code here. } }
// This is the key to fix our problem
AndroidView(factory = {
NestedScrollView(it)
}, update = {
it.layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT)
// Update scroll state of NestedScrollView via LazyListState of LazyColumn
it.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->
if (scrollY != oldScrollY && scrollState.firstVisibleItemIndex != 0 && scrollState.lastVisibleItemIndex != 99) {
scrollState.scrollToItem(0)
}
}
}) { view ->
// Add LazyColumn into NestedScrollView
(view as NestedScrollView).addView(scrollState.layoutInfo.visibleItemsInfo[0].composed)
}
}
}