[英]Jetpack Compose LazyColumn Scroll Listener
As Ryan M writes , you can use LazyListState.firstVisibleItemIndex
.正如Ryan M 所写,您可以使用
LazyListState.firstVisibleItemIndex
。 The magic of Compose is that you can just use it in an if
statement and Compose will do the work. Compose 的神奇之处在于,您只需在
if
语句中使用它,Compose 就会完成这项工作。 Look at the following example, which displays a different text based on the first visible item.请看以下示例,该示例根据第一个可见项目显示不同的文本。 Similarly, you can select a different tab based on the first visible item.
同样,您可以 select 基于第一个可见项目的不同选项卡。
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val listState = rememberLazyListState()
Column {
Text(if (listState.firstVisibleItemIndex < 100) "< 100" else ">= 100")
LazyColumn(state = listState) {
items(1000) {
Text(
text = "$it",
modifier = Modifier.fillMaxWidth(),
)
}
}
}
}
}
}
You can use the LazyListState.firstVisibleItemIndex
property (obtained via rememberLazyListState
and set as the state
parameter to LazyColumn
) and set the current tab based on that.您可以使用
LazyListState.firstVisibleItemIndex
属性(通过rememberLazyListState
获得并将state
参数设置为LazyColumn
)并基于该属性设置当前选项卡。
Reading that property is considered a model read in Compose, so it will trigger a recomposition whenever the first visible item changes.读取该属性被认为是在 Compose 中读取的 model,因此只要第一个可见项发生更改,它将触发重新组合。
If you instead want to do something more complex based on more than just the first visible item, you can use LazyListState.layoutInfo
to get information about all visible items and their locations, rather than just the first.如果您想要做的不仅仅是基于第一个可见项目的更复杂的事情,您可以使用
LazyListState.layoutInfo
来获取有关所有可见项目及其位置的信息,而不仅仅是第一个。
Just create a NestedScrollConnection
and assign it to parent view nestedScroll
modifier:只需创建一个
NestedScrollConnection
并将其分配给父视图nestedScroll
修饰符:
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val delta = available.y
// called when you scroll the content
return Offset.Zero
}
}
}
Assign it to LazyColumn
or to its parent composed view:将其分配给
LazyColumn
或其父组合视图:
Modifier.nestedScroll(nestedScrollConnection)
Exemple:示例:
LazyColumn(
...
modifier = Modifier.nestedScroll(nestedScrollConnection)
) {
items(...) {
Text("Your text...")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.