用户在 TextField Jetpack Compose 中输入文本后显示尾随图标

Mr.*_*hie 8 android textfield android-jetpack-compose kotlin-android

我在尝试着:

  1. 仅当用户输入空格以外的某些文本时,才使可组合trailingIcon项可见。TextField
  2. 稍后,当用户单击时,应该清除trailingIcon其中的文本,并且应该消失。TextFieldtrailingIcon
  3. 同样,当用户输入空格以外的文本时,trailingIcon应该出现 并启用此文本清除功能。

等等...

我尝试寻找这个问题的解决方案,但大多数都关注“可见trailingIcons”,而不是我想要实现的。

Phi*_*hov 17

根据文本状态,您可以指定参数null或实际视图trailingIcon

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,
)
Run Code Online (Sandbox Code Playgroud)


Gab*_*tti 8

您可以添加条件以使trailingIcon.

就像是:

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"
                )
            }
        }
    }
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述