Search code examples
androidandroid-jetpack-composeandroid-jetpack-compose-text

Jetpack Compose how to center hint and input inside BasicTextField


I'm trying to make an editText which fills the width of the screen, and it's hint and input starts from the center of the screen.

I choose BasicTextField, since the styles of TextField and OutlinedTextFields are completely unnecessary to me.

I've tried doing this.

      BasicTextField(
                value = loginId,
                onValueChange = {
                    loginId = it
                },
                decorationBox = {
                     Text(text = "Input your id", modifier = Modifier.align(Alignment.CenterHorizontally).fillMaxWidth())
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 19.dp,
                        bottom = 4.5.dp, end = 19.dp, top = 40.dp)
                    .background(Purple200)
                    .align(Alignment.CenterHorizontally),
            )

This has no effect. What can I do with this?


Solution

  • You can apply TextAlign.Center to your Text. You can use the style or the textAlign properties. Something like:

    Text(text = "Input your id",
                    modifier = Modifier.fillMaxWidth(),
                    style = LocalTextStyle.current.copy(textAlign = TextAlign.Center))
    

    or:

     Text(text = "Input your id",
                        modifier = Modifier.fillMaxWidth(),
                        textAlign = TextAlign.Center)
    

    enter image description here

    Also to work correctly, since you are using the decorationBox, you must call innerTextField exactly once inside your decorationBox. Something like:

     decorationBox = {  innerTextField ->
            //....
            if (loginId.isEmpty()) {
                Text("....")
            }
            innerTextField()  //<-- Add this
      }