Search code examples
androidandroid-jetpack-composeandroid-appbarlayout

Center TextField in MediumTopAppBar title


WHAT I AM TRYING TO DO: I am trying to use a TextField inside the title of MediumTopAppBar. THE PROBLEM: The TextField looks like it's been cut off from the top.

MY CODE

Scaffold(
        topBar = {
            MediumTopAppBar(
                title = {    

                    TextField(
                        value = "",
                        onValueChange = {/*TODO*/},
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(0.dp)
                            .height(40.dp)
                            .zIndex(1f)
                            .border(0.dp, Color.Transparent, RoundedCornerShape(8.dp)),
                        colors = TextFieldDefaults.textFieldColors(
                            textColor = Color.Gray,
                            disabledTextColor = Color.Transparent,
                            focusedIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            disabledIndicatorColor = Color.Transparent
                        ),
                        shape = RoundedCornerShape(8.dp)
                    )

                },
......

I tried to set the heigh of the TextField with smaller number

How it looks like


Solution

  • Use a BasicTextField instead of a TextField:

    MediumTopAppBar(
        title = {
            BasicTextField(
                value = text,
                onValueChange = { text = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(0.dp)
                    .height(40.dp)
                    .zIndex(1f)
                    .border(0.dp, Color.Transparent, RoundedCornerShape(8.dp)),
                interactionSource = interactionSource,
                enabled = enabled,
                singleLine = singleLine
            ){
                TextFieldDefaults.TextFieldDecorationBox(
                    value = text,
                    innerTextField = it,
                    enabled = enabled,
                    singleLine = singleLine,
                    visualTransformation = VisualTransformation.None,
                    interactionSource = interactionSource,
                    contentPadding = TextFieldDefaults.textFieldWithoutLabelPadding(
                        top = 0.dp,
                        bottom = 0.dp
                    ),
                    colors = TextFieldDefaults.textFieldColors(
                        textColor = Color.Gray,
                        disabledTextColor = Color.Transparent,
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        disabledIndicatorColor = Color.Transparent
                    ),
                )
            }
        },