Home > Enterprise >  Android Jetpack - Remove Top Padding of OutlinedTextField with Label
Android Jetpack - Remove Top Padding of OutlinedTextField with Label

Time:08-29

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?

CodePudding user response:

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

  • Related