簡體   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