Jetpack Compose:如何将UI元素放置在具有精确(x,y)坐标的父元素中?



根据自定义布局的文档:"每个UI元素有一个父元素和可能的多个子元素。每个元素也位于它的父元素中,指定为(x, y)位置和大小,指定为宽度和高度。">

假设我在一个盒子里面有一个按钮。我如何为该框内的按钮指定确切的X和Y位置?

默认BoxTopStart对齐,与android坐标空间起点相同。要从该点移动,可以使用offset修饰符:

Box {
Button(
onClick = { /*TODO*/ },
modifier = Modifier
.offset(x = 100.dp, y = 100.dp)
) {
}
}

对于自定义布局,情况有点不同。你可以在Layouts Codelab - https://developer.android.com/codelabs/jetpack-compose-layouts#6

中阅读所有这些内容。说明如何手工设计一个列。

示例,在给定的约束条件中居中元素。

Layout(
content = {
Button(onClick = { /*TODO*/ }) {
Text("Lorem Ipsum")
}
}
){measurables, constraints ->
//Measuring the First (and only) item with the given constraints and storing the resulting placeable
val placeable = measurables[0].measure(constraints)
layout(constraints.maxWidth, constraints.maxHeight){ // Size of the Layout, can be anything you want, even a number
placeable.place(constraints.maxWidth / 2, constraints.maxHeight / 2) // Placing at net half the distance
//You can also specify the x, y above. That is what it is for.
}
}

就这些

modifier = Modifier.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
//  placeable.placeRelative(x.roundToPx(), y.roundToPx())
placeable.place(IntOffset(it.offset.x.roundToInt(), it.offset.y.roundToInt()))
}
}

最新更新