Android Compose:将一个元素放置在中心,将其他元素放置在其上方

Qen*_*Bau 4 user-interface android android-jetpack-compose

我需要Text("text center")在屏幕中心插入一个文本元素(水平和垂直)。另外,我想在Text("text")上面的元素Text("text center")中插入一个空格32dp在此输入图像描述

例如,以下代码不正确,因为整个块居中而不仅仅是“文本中心”:

 Column(
    modifier = Modifier
        .fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center,
) {
    Text(text = "text")
    Spacer(modifier = Modifier.height(32.dp))
    Text(text = "text center")
}
Run Code Online (Sandbox Code Playgroud)

Ma3*_*a3x 9

您可以使用 ,ConstraintLayout因为仅使用标准库中的可组合项来正确完成这种类型的布局会有点麻烦。

ConstraintLayout 可以帮助在屏幕上相对于其他可组合项放置可组合项,并且是使用多个嵌套行、列、框和自定义布局元素的替代方法。

将其添加到您的app.gradle文件中

implementation "androidx.constraintlayout:constraintlayout-compose:1.0.1"
Run Code Online (Sandbox Code Playgroud)

并同步项目,以便 Gradle 下载依赖项。截至 2022 年 7 月,稳定版本为1.0.1.

您的布局需要以下约束:

  1. “中心文本”需要水平和垂直居中到父级
  2. “顶部文本”需要与父级水平居中
  3. 32 dp“顶部文本”的底部和“中心文本”的顶部之间应该有一个边距

在代码中,这些约束是这样指定的

implementation "androidx.constraintlayout:constraintlayout-compose:1.0.1"
Run Code Online (Sandbox Code Playgroud)

由于有关 compose 版本的官方文档ConstraintLayout非常有限,因此如果您需要更多示例,可以检查使用它的 compose 示例

不过,Widget(非 compose)版本的官方文档ConstraintLayout很好,因此要了解它可以执行的所有操作,您可以查看https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout

也许某些功能在 compose 版本中尚不可用。截至 2022 年 7 月,最新的 alpha 版本是1.1.0-alpha03

implementation "androidx.constraintlayout:constraintlayout-compose:1.1.0-alpha03"
Run Code Online (Sandbox Code Playgroud)