简体   繁体   English

如何在 Jetpack Compose 的文本字段中为图标的可见性设置动画

[英]How to animate visibilty of icon within text field in Jetpack Compose

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.当我输入文本并且当TextField文本为空时,我试图为TextField中的trailingIcon的可见性设置动画,但由于某种原因,发生这种情况时没有任何反应。

Previous code (before using AnimatedVisibility )以前的代码(在使用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 )当前代码(使用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"
                )
            }
        }
    }
)

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"
                )
            }
        }
    }
)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM