如何在 Jetpack Compose 中将列内的元素居中

Tig*_*yan 4 android android-layout kotlin android-jetpack android-jetpack-compose

如何将嵌入行内的第一个列中的元素居中:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MaterialTheme {
                Row {
                    Column(modifier = LayoutPadding(top = 16.dp)) {
                        Text(text = "Centered ", style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.Bold))
                    }
                    Column {
                        Text(text = "Line One ", style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.Bold))
                        Text(text = "Line Two ", style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.Bold))
                    }
                 }
             }
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,我对填充进行了硬编码,但无法弄清楚如何将元素置于框外居中。如果没有这样的选项,我怎样才能得到整行的高度?

Gab*_*tti 7

您可以Modifier.align在您的Column

Row (){
    Column( modifier = Modifier.align(Alignment.CenterVertically)){
        Text(text = "Centered ", style = textStyle)
    }
    Column {
        Text(text = "Line One ", style = textStyle)
        Text(text = "Line Two ", style = textStyle)
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

verticalAlignment = Alignment.CenterVertically或者您可以在元素中使用Row

Row (verticalAlignment = Alignment.CenterVertically){
    Column(){
        Text(text = "Centered ", style = textStyle)
    }
    Column() {
        Text(text = "Line One ", style = textStyle)
        Text(text = "Line Two ", style = textStyle)
    }
}
Run Code Online (Sandbox Code Playgroud)