March3April4
March3April4

Reputation: 2291

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?

Upvotes: 7

Views: 7864

Answers (2)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364868

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
  }

Upvotes: 8

Jimmy
Jimmy

Reputation: 68

Text Composable have textAlign parameter, so you can simply centre your text using this parameter :

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

enter image description here

Reference: https://developer.android.com/jetpack/compose/text#text-alignment

Upvotes: 0

Related Questions