Jetpack Compose - 如何在 BasicTextField 中显示 trailingIcon?

3
TextField默认的填充太多,不适用于我正在构建的屏幕,因此我被迫使用BasicTextField(参见:这篇有关默认TextField填充的帖子)。

问题是,BasicTextField没有trailingIcon参数。有什么办法可以解决这个问题吗?


你想在使用 BasicTextField 的同时添加 leadingIcon/trailingIcon 吗?还是你想使用 TextField/OutlinedTextField 并能够设置所有的填充?此外,你需要 Compose 版本 1.1.x 的解决方案,还是 > 1.2.0-beta 也可以(因为 DecorationBox 默认已在其中一个 1.2.0 alpha 版本中公开,这样可以提供更好的解决方案)?解决此问题的一种方法是使用 Compose 版本 1.2.0-beta+,并手动公开 TextField 和/或 OutlinedTextFieldcontentPadding 参数。 - Ma3x
1个回答

4

从1.2.0开始,您可以在BasicTextField中使用TextFieldDecorationBox。 在这里,您可以使用trailingIconcontentPadding属性:

BasicTextField(
    value = value,
    onValueChange = onValueChange,        
    interactionSource = interactionSource,
    enabled = enabled,
    singleLine = singleLine
) {
    TextFieldDefaults.TextFieldDecorationBox(
        value = value,
        innerTextField = it,
        singleLine = singleLine,
        enabled = enabled,
        visualTransformation = VisualTransformation.None,
        trailingIcon = { /* ... */ },
        interactionSource = interactionSource,
        contentPadding = TextFieldDefaults.textFieldWithoutLabelPadding(
               //...top = 0.dp, bottom = 0.dp
        )
    )
}

当使用 kotlinCompilerExtensionVersion = "1.5.1""androidx.compose:compose-bom:2023.08.00" 时,TextFieldDefaults.TextFieldDecorationBox 已被弃用。替代方案是 TextFieldDefaults.DecorationBox - undefined
如果您的BasicTextField使用了decorationBox = { innerTextField -> ... },那么您必须像这个答案中所示使用innerTextField属性:https://stackoverflow.com/questions/68600128/remove-default-padding-on-jetpack-compose-textfield#71305641 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接