Home > Net >  How to animate visibilty of icon within text field in Jetpack Compose
How to animate visibilty of icon within text field in Jetpack Compose

Time:12-28

I am trying to animate the visibility of a trailingIcon within a TextField when I enter text and when the TextField text is empty, but for some reason, nothing happens when this happrns.

Previous code (before using AnimatedVisibility)

TextField(
    modifier = Modifier.fillMaxWidth(),
    value = mText,
    onValueChange = {
        mText = it
    },
    trailingIcon = {
        when {
            mText.isNotEmpty() -> OutlinedIconButton(
                onClick = { mText = "" }
            ) {
                Icon(
                    imageVector = Icons.Default.Clear,
                    contentDescription = "Clear"
                )
            }
        }
    }
)

Current code (after using AnimatedVisibility)

OutlinedTextField(
    modifier = Modifier.fillMaxWidth(),
    value = mText,
    onValueChange = {
        mText = it
    },
    trailingIcon = {
        AnimatedVisibility(
            visible = visible,
            enter = fadeIn(),
            exit = fadeOut()
        ) {
            IconButton(
                    onClick = { mText = "" }
            ) {
                Icon(
                    imageVector = Icons.Default.Clear,
                    contentDescription = "Clear"
                )
            }
        }
    }
)

CodePudding user response:

You can use something like:

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

OutlinedTextField(
    value = text,
    onValueChange = {
        text = it
    },
    trailingIcon = {
        AnimatedVisibility(
            visible = isVisible,
            enter = fadeIn(),
            exit = fadeOut()
        ) {
            IconButton(
                onClick = { text = "" }
            ) {
                Icon(
                    imageVector = Icons.Default.Clear,
                    contentDescription = "Clear"
                )
            }
        }
    }
)

enter image description here

  • Related