Custom TextField in Jetpack Compose

187 Views Asked by At

I am trying to design the TextField (based on the layout based styles of TextInputLayout and TextInputEditText). I need to achieve the below design. Like, the error message should appear below the TextField.

enter image description here

But I couldn't now. I can able to achieve the below.

enter image description here

The composable code:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TextInputField(isError: Boolean = false, isEnabled: Boolean = true) {
    val interactionSource = MutableInteractionSource()
    val isFocused by interactionSource.collectIsFocusedAsState()

    var text by remember { mutableStateOf(TextFieldValue("")) }
    var isErrorValue by remember { mutableStateOf(true) }
    TextField(
        value = text,
        onValueChange = { newValue -> text = newValue },
        modifier = Modifier
            .padding(8.dp)
            .fillMaxWidth(),
        label = {
            Text(
                text = "Email",
                style = textInputHelperTextAppearance
            )
        },
        placeholder = {
            Text(
                text = "",
                style = textInputHintTextAppearance
            )
        },
        colors = TextFieldDefaults.textFieldColors(
            cursorColor = TOOLKIT_ERROR_COLOR,
            containerColor = getTextFieldBackgroundColor(
                isFocused = isFocused, isDisabled = isEnabled
            ),
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent
        ),
        isError = isError,
        supportingText = {
            if (isError)
                Text(
                    text = "Enter a valid Email Address",
                    style = textInputErrorTextApperance
                )
        },
        textStyle = getTextInputEditTextAppearance(isEnabled),
        interactionSource = interactionSource
    )
}

How could I achieve the required design?

1

There are 1 best solutions below

0
Name On

I coded a simple example. You can customize it however you want.

@Preview()
@Composable
fun CustomTextInputField(
    isError: Boolean = true, isEnabled: Boolean = true
) {
    var value by remember {
        mutableStateOf(TextFieldValue(""))
    }

    OutlinedTextField(
        modifier = Modifier
            .padding(5.dp)
            .fillMaxWidth(),
        value = value,
        onValueChange = {
            value = it
        },
        label = {
            Text(text = "Email")
        },
        supportingText = {
            if (isError)
                Text(
                    text = "Enter a valid Email Address",
                )
        },
        isError = isError,
        colors = OutlinedTextFieldDefaults.colors(

        )
    )
}

Material version:

implementation 'androidx.compose.material3:material3:1.2.0-alpha11'

Output: