androidkotlinandroid-jetpack-composeandroid-jetpack-compose-layout

Kotlin Compose, Align items in row


I'm using the brand new Kotlin Compose for my view, I have a row with 2 items, how can I make them center-vertical-like?

    Row(
            modifier = Spacing(20.dp)
    ) {
        Text(text = "Hello $name!")
        Spacing(10.dp)
        Padding(padding = 25.dp) {
            Button(text = "Click", onClick = { /*do something*/ })

        }
    }

enter image description here

Note that without padding they are not aligned too.


Solution

  • There's verticalAlignment argument in Row. You can also configure an item alignment individually using align modifier which overrides the row's verticalAlignment. For example:

    @Composable
    fun RowAlignmentExample() {
        Row(verticalAlignment = Alignment.CenterVertically) {
            SizeTile(14)
            SizeTile(18)
            SizeTile(22)
            SizeTile(26)
            SizeTile(10, modifier = Modifier.align(Alignment.Top))
            SizeTile(10, modifier = Modifier.align(Alignment.Bottom))
        }
    }
    
    @Composable
    fun SizeTile(fontSize: Int, modifier: Modifier = Modifier) {
        Text(
            text = fontSize.toString(),
            fontSize = fontSize.sp,
            modifier = modifier
                .padding(2.dp)
                .background(Color.White, RoundedCornerShape(4.dp))
                .padding(2.dp)
        )
    }
    

    enter image description here