Show trailing icon after text input from user in TextField Jetpack Compose

14.2k views Asked by At

I am trying to:

  1. make the trailingIcon of TextField composable visible only if the user enters some text other than white spaces.
  2. Later when the user clicks the trailingIcon the text in the TextField should get cleared and the trailingIcon should disappear.
  3. Again when the user enters a text other than space, the trailingIcon should appear and enable this text clearing feature.

and so on...

I tried searching for solutions to this problem but mostly they were focused on "visible trailingIcons" and not what I was trying to implement.

2

There are 2 answers

0
Phil Dukhov On BEST ANSWER

Depending on text state you can specify null or actual view for trailingIcon parameter:

var text by remember { mutableStateOf("") }
val trailingIconView = @Composable {
    IconButton(
        onClick = {
            text = ""
        },
    ) {
        Icon(
            Icons.Default.Clear,
            contentDescription = "",
            tint = Color.Black
        )
    }
}
TextField(
    value = text,
    onValueChange = { text = it },
    trailingIcon = if (text.isNotBlank()) trailingIconView else null,
)
0
Gabriele Mariotti On

You can add a condition to make visible the trailingIcon.

Something like:

var text by remember { mutableStateOf("") }
val isVisible by remember {
    derivedStateOf {
        text.isNotBlank()
    }
}

OutlinedTextField(
    value = text,
    onValueChange = {
        text = it
    },
    trailingIcon = {
        if (isVisible) {
            IconButton(
                onClick = { text = "" }
            ) {
                Icon(
                    imageVector = Icons.Default.Clear,
                    contentDescription = "Clear"
                )
            }
        }
    }
)

enter image description here