alfietap
alfietap

Reputation: 2279

Jetpack Compose Textfield Label not staying in center

I'm trying to make a textfield thats quite small (32.dp). When doing this, the label gets pushed to the bottom and I can't find a way to keep it centered? I've tried using TextAlign.center but no luck

TextField(
            modifier = Modifier
                .height(32.dp)
                .padding(horizontal = 8.dp)
                .border(1.dp, colorResource(id = R.color.mono4), RoundedCornerShape(32.dp))
                .constrainAs(commentBox) {
                    top.linkTo(parent.top)
                    bottom.linkTo(parent.bottom)
                    start.linkTo(profilePhoto.end)
                    end.linkTo(postText.start)
                    width = Dimension.fillToConstraints
                    height = Dimension.fillToConstraints
                },
            label = {
                Text(
                    textAlign = TextAlign.Center,
                    text = "Comment on workout...",
                    style = TextStyle(
                        fontSize = 14.sp,
                        color = colorResource(id = R.color.mono4),
                        fontFamily = FontFamily(Font(R.font.josefin_san_regular))
                    )
                )
            },
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent
            ),
            value = commentText,
            onValueChange = { commentText = it }
        )

enter image description here

Upvotes: 3

Views: 2320

Answers (1)

Richard Onslow Roper
Richard Onslow Roper

Reputation: 6863

This is internal behaviour, you will need to alter the source coe to fix it, or implement your own composable, something like:-

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun TinyTextCapture(){
    var value by remember { mutableStateOf("") }
    Box(contentAlignment = Alignment.Center){
        TextField(
            modifier = Modifier.height(32.dp),
            value = value, onValueChange = { value = it }
        )
        AnimatedVisibility(visible = value.isEmpty()) {
            Text("Label")
        }
    }

}

The default label parameter has a default padding from top start, that is why it was seen as being pushed downwards. If I were you, I would not go about editing the source of something as basic as a TextField since it has so many internal dependencies that it is all a mess.

You could also do without the AnimatedVisibility, and also apply a ConstraintLayout to get it at the start of the TextField in contrast to its absolute centered position right now.

Works like a charm

Upvotes: 2

Related Questions