Search code examples
androidalignmentrowandroid-jetpack-compose

Android Basic TextField alignment in Jetpack Compose


i am having problemas trying to align text in a BasicTextField inside a ROW in Jetpack Compose, the goal is to have the text in total center.

The code is the following:

Row(verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {

        BasicTextField(
            modifier = Modifier
                .height(40.dp)
                .align(Alignment.CenterVertically),
            value = "Hello",
            onValueChange = {},
            singleLine = true,
            textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.Center),
        )
    }

Here is a picture of the result:

enter image description here

Any ideas what's wrong?

Thanks!

Ariel


Solution

  • I found 2 ways to solve this problem:

    The first is simpler if BasicTextField does not necessarily need to have a height of 40.dp, and the Row component can be responsible for setting a height:

    Row(
        modifier = Modifier.height(40.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        BasicTextField(
            value = "Hello",
            onValueChange = {},
            singleLine = true,
            textStyle = LocalTextStyle.current.copy(textAlign = TextAlign.Center),
        )
    }
    

    The second way is in case your BasicTextField really needs to have a height of 40dp, and this responsibility cannot be assigned to the parent component (Row).

    The strategy here is to wrap the BasicTextField with a box height of 40dp and then align it to the center of the parent:

    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        Box(
            modifier = Modifier.height(40.dp),
            contentAlignment = Alignment.Center,
        ) {
            BasicTextField(
                value = "Hello",
                onValueChange = {},
                textStyle = TextStyle(textAlign = TextAlign.Center)
            )
        }
    }
    

    Note that in this second case it was necessary to change the assignment of the textStyle parameter of the BasicTextField:

    Row(...) {
         BasicTextField(
              ...
             textStyle = TextStyle(textAlign = TextAlign.Center)
         )
    }
    

    For both cases the visual result will be this:

    enter image description here