gpt4 book ai didi

android - Jetpack Compose - 修饰符的顺序

转载 作者:行者123 更新时间:2023-12-03 23:11:33 26 4
gpt4 key购买 nike

文档说修饰符是从左侧应用的。
但从这个例子来看,它们似乎是从右边应用的:
第一个边框,然后填充,因为文本和边框之间没有空格

Text("Hi there!", Modifier.padding(10.dp).border(2.dp, Color.Magenta))
enter image description here

最佳答案

Layouts in Jetpack Compose包含 Layout modifiers under the hood 的代码实验室解释修饰符顺序的步骤,请参阅“顺序事项”部分。

order matters when chaining modifiers as they're applied to the composable they modify from earlier to later, meaning that the measurement and layout of the modifiers on the left will affect the modifier on the right. The final size of the composable depends on all modifiers passed as a parameter. First, modifiers will update the constraints from left to right, and then, they return back the size from right to left.


为了更好地理解它,我建议弄清楚 layouts在 Compose 中工作。简而言之, padding()LayoutModifer ,它接受一些约束,根据该约束的投影测量其子大小,并将子放置在某些坐标处。
让我们看一个例子:
Box(
modifier = Modifier
.border(1.dp, Color.Red)
.size(32.dp)
.padding(8.dp)
.border(1.dp, Color.Blue)
)
结果:
enter image description here
但是让我们交换 .size().padding()
Box(
modifier = Modifier
.border(1.dp, Color.Red)
.padding(8.dp)
.size(32.dp)
.border(1.dp, Color.Blue)
)
现在我们得到了不同的结果:
enter image description here
我希望这个示例可以帮助您弄清楚修饰符是如何应用的。
可以预期,红色边框应该是最接近盒子的,因为它是最先添加的,所以顺序可能看起来颠倒了,但这样的顺序也有优点。让我们来看看这个可组合的:
@Composable
fun MyFancyButton(modifier: Modifier = Modifier) {
Text(
text = "Ok",
modifier = modifier
.clickable(onClick = { /*do something*/ })
.background(Color.Blue, RoundedCornerShape(4.dp))
.padding(8.dp)
)
}
只需移动 modifier可组合的参数允许其父级添加额外的修饰符,例如额外的边距。因为最后添加的修饰符离按钮最近,所以边框和内部填充不会受到影响。

关于android - Jetpack Compose - 修饰符的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64206648/

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