gpt4 book ai didi

android - 如何实现 LazyColumn 项目印象跟踪

转载 作者:行者123 更新时间:2023-12-05 04:21:45 25 4
gpt4 key购买 nike

我有一个带有项目的惰性列,我想在每次其中一个项目出现在屏幕上时发送一个事件。有第一次发送事件的示例(如此处 https://plusmobileapps.com/2022/05/04/lazy-column-view-impressions.html ),但该示例不会在随后再次出现相同项目时发送事件(例如,向上滚动时)。

我知道它不应该与构图联系在一起,因为当一个项目保留在屏幕上时可以进行多次重新构图。解决此类问题的最佳方法是什么?

最佳答案

我修改了文章中的示例,从键到索引,它工作正常,你应该检查键匹配是否有问题。

@Composable
private fun MyRow(key: Int, lazyListState: LazyListState, onItemViewed: () -> Unit){
Text(
"Row $key",
color = Color.White,
modifier = Modifier
.fillMaxWidth()
.background(Color.Red)
.padding(20.dp)
)

ItemImpression(key = key, lazyListState = lazyListState) {
onItemViewed()
}
}


@Composable
fun ItemImpression(key: Int, lazyListState: LazyListState, onItemViewed: () -> Unit) {

val isItemWithKeyInView by remember {
derivedStateOf {
lazyListState.layoutInfo
.visibleItemsInfo
.any { it.index == key }
}
}

if (isItemWithKeyInView) {
LaunchedEffect(Unit) {
onItemViewed()
}
}
}

然后用作

LazyColumn(
verticalArrangement = Arrangement.spacedBy(14.dp),
state = state
) {
items(100) {
MyRow(key = it, lazyListState = state) {
println("🔥 Item $it is displayed")
if(it == 11){
Toast.makeText(context, "item $it is displayed", Toast.LENGTH_SHORT).show()
}
}

}
}

结果

enter image description here

此外,您可以将 ItemImpression 作为仅使用状态跟踪事件的可组合项移动到列表上方,而不是将 LazyListState 发送到每个 ui 可组合项。我放了 2,但你也可以发送一个列表并为多个列表创建

@Composable
private fun LazyColumnEventsSample() {

val context = LocalContext.current
val state = rememberLazyListState()

ItemImpression(key = 11, lazyListState = state) {
Toast.makeText(context, "item 11 is displayed", Toast.LENGTH_SHORT).show()
}


ItemImpression(key = 13, lazyListState = state) {
Toast.makeText(context, "item 13 is displayed", Toast.LENGTH_SHORT).show()
}


LazyColumn(
verticalArrangement = Arrangement.spacedBy(14.dp),
state = state
) {
items(100) {
Text(
"Row $it",
color = Color.White,
modifier = Modifier
.fillMaxWidth()
.background(Color.Red)
.padding(20.dp)
)
}
}
}

关于android - 如何实现 LazyColumn 项目印象跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74157909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com