Android Jetpack – Remove Top Padding of OutlinedTextField with Label

Issue

I’ve simple OutlinedTextField:


OutlinedTextField(
                    modifier = Modifier.fillMaxWidth().background(Color.White, RoundedCornerShape(12.dp)),
                    value = enteredTextPassword,
                    onValueChange = { enteredTextPassword = it },
                    shape = RoundedCornerShape(16.dp),
                    placeholder = { Text(text = "Password", color = Color.Gray)},
                    singleLine = true,
                    label = { Text("Password", color = Color.Gray) }
                )

My outputs are:

  • Normal

enter image description here

  • Filled & Focused

enter image description here

Filled&Focused output is acceptable for me but as you see there is little top padding in Normal output.

Normally, I’m trying to get these outputs:

  • Normal

enter image description here

  • Filled&Focused

enter image description here

How can I remove my top padding on Normal output ? Or, is there anyway to get exact outputs which I mentioned last?

Solution

For a simple example, you can wrap the TextField in a Box like this and handle the border color using the Box.

This method has a lot of limitations in terms of padding, placement, etc. For more customizations, use a BasicTextField

@Composable
fun SimpleCustomTextField(
    text: String,
    setText: (text: String) -> Unit,
    modifier: Modifier = Modifier,
    label: @Composable (() -> Unit)? = null,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    colors: TextFieldColors = TextFieldDefaults.outlinedTextFieldColors(),
    shape: Shape = RoundedCornerShape(12.dp),
) {
    val color: State<Color> = colors.indicatorColor(
        enabled = true,
        isError = false,
        interactionSource = interactionSource,
    )

    Box(
        contentAlignment = Alignment.BottomStart,
        modifier = modifier
            .fillMaxWidth()
            .clip(shape)
            .background(White),
    ) {
        OutlinedTextField(
            value = text,
            onValueChange = setText,
            colors = TextFieldDefaults.outlinedTextFieldColors(
                focusedBorderColor = Transparent,
                disabledBorderColor = Transparent,
                errorBorderColor = Transparent,
                unfocusedBorderColor = Transparent,
            ),
            label = label,
            interactionSource = interactionSource,
            modifier = Modifier
                .fillMaxWidth()
                .clip(shape)
                .border(
                    width = 1.dp,
                    color = color.value,
                    shape = shape,
                ),
        )
    }
}

Default

Default

Focused

Focused

Answered By – Abhimanyu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published