繁体   English   中英

布局在 Jetpack Compose 中如何工作以及它们与 XML 有何关系?

[英]How do layouts work in Jetpack Compose and how do they relate to XML?

我有一些文字。 我想在屏幕上居中。 我正在使用 Jetpack Compose。 我该怎么做呢? 我知道 Jetpack Compose 中有三种类型的布局。

  • 盒子
  • 柱子
  • 水平的

我应该使用哪一个? 我不知道布局是如何工作的。 它们是否像 XML 一样默认全屏显示? 如果是这样,我如何 position 元素,如 ConstraintLayout? 如何仅从一侧设置填充和边距以及如何链接元素?

我想如果您遵循Compose Pathway ,您的所有问题都会得到澄清。 但我会尽力为你总结......

您可以使用以下“布局管理器”之一(在 Compose 中称为布局)来组织您的组件:

  • Column (类似于具有垂直方向的LinearLayout
  • Row (类似于具有水平方向的LinearLayout
  • Box (类似于FrameLayout
  • ConstraintLayout 如果您需要这些不同的东西,您可以使用Layout可组合项创建自定义布局。

“我应该使用哪一个?” 您可以根据具体情况使用其中的任何一种... 要在屏幕中央简单地显示文本,您可以使用所有这些来实现。

使用Column

Column(
    Modifier.fillMaxSize(), // to fill the whole screen
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    Text(text = "Hello")
}

使用Box

Box(
    Modifier.fillMaxSize()
) {
    Text(text = "Hello",
        modifier = Modifier.align(Alignment.Center))
}

“它们是否像 XML 一样默认全屏显示?” 不,默认情况下它们是“wrap_content”。

“我如何 position 元素,如 ConstraintLayout?如何仅从一侧设置填充和边距以及如何链接元素?” 您需要声明对组件的引用,然后相应地定位它们。

这是一个简单的例子......

ConstraintLayout(modifier = Modifier.fillMaxSize().padding(16.dp)) {
    // Creating refs...
    val (text1Ref, edit1Ref, btn1Ref, btn2Ref) = createRefs()
    Text("Name", 
        // Linking the reference to this component
        modifier = Modifier.constrainAs(text1Ref) {
        // linking the top of this component to the parent top
        top.linkTo(parent.top)
        centerHorizontallyTo(parent)
    })
    TextField(
        value = "",
        onValueChange = {},
        label = { Text("Name") },
        modifier = Modifier.padding(top = 8.dp)
            .constrainAs(edit1Ref) {
                start.linkTo(parent.start)
                end.linkTo(parent.end)
                // linking this component with the previous component
                top.linkTo(text1Ref.bottom)
            })
    Button(onClick = {},
        content = { Text("OK") },
        modifier = Modifier.padding(top = 8.dp).constrainAs(btn1Ref) {
            end.linkTo(edit1Ref.end)
            top.linkTo(edit1Ref.bottom)
        }
    )
    TextButton(onClick = {},
        content = { Text("Cancel") },
        modifier = Modifier.padding(end = 8.dp)
            .constrainAs(btn2Ref) {
                end.linkTo(btn1Ref.start)
                baseline.linkTo(btn1Ref.baseline)
            }
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM