我正在开发compose基于UI的android应用程序。我需要得到可堆肥的尺寸,并在每次真正的变化时都得到尺寸。我检查了onSizeChanged的基本代码。onSizeChanged创建扩展OnRemeasuredModifier的修饰符,并存储以前的大小,但每次重新组合后,以前的大小都会重置,这会导致无限次调用onSizeChanned。我试着镇定下来,但无济于事。这是一个示例代码:
var counter by remember { mutableStateOf(0) }
LaunchedEffect(key1 = counter, block = {
delay(1000)
counter++
})
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier
.onSizeChanged {
it
}
.composed {
Modifier.onSizeChanged {
it
}
},
text = "Hello, $counter!",
color = Color.Black
)
}
}
我实现的解决方案是记住onSizeChanged修饰符来保存以前的大小。但我不确定这是否是正确的方式。
var counter by remember { mutableStateOf(0) }
LaunchedEffect(key1 = counter, block = {
delay(1000)
counter++
})
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier
.onSizeChanged {
it
}
.composed {
Modifier.onSizeChanged {
it
}
}
.remembered {
Modifier.onSizeChanged {
it
}
},
text = "Hello, $counter!",
color = Color.Black
)
}
}
我试着作曲,但无济于事。所以我创建了记忆函数:
@Composable
fun Modifier.remembered(modifier: () -> Modifier): Modifier {
val rememberedModifier = remember {
modifier()
}
return then(rememberedModifier)
}