You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose:为BasicTextField实现文本末尾省略号效果

实现带省略号的金额输入框及货币联动转换

我在项目中需要实现两个金额输入框,用户输入其中一个时,另一个会自动显示对应货币的转换值。同时,我需要在BasicTextField中实现长文本末尾显示省略号的效果,以下是我的实现代码:

var focused by remember { mutableStateOf(false) }

var textState by remember(state.amount) {
    mutableStateOf(TextFieldValue(""))
}


if (!amountsEqual(state.amount.toBigDecimalOrNull(), textState.text.toBigDecimalOrNull())) {
    if (!state.dimAmount || state.amount.isNotEmpty()) {
        val text = if (!focused) state.amount.shortedBy(17) else state.amount
        textState = textState.copy(text = text, selection = TextRange(text.length))
    }
}

val textColor = when {
    state.dimAmount -> Colors.grey50
    else -> Colors.leah
}

BasicTextField(
        modifier = Modifier
            .onFocusChanged { focusState ->
                focused = focusState.isFocused
                onFocusChanged?.invoke(focusState.isFocused)
            }
            .focusRequester(focusRequester)
            .fillMaxWidth(),
        value = textState,
        enabled = state.amountEnabled,
        singleLine = true,
        onValueChange = { textFieldValue ->
            if (isValid(textFieldValue.text, state.validDecimals)) {
                textState = textFieldValue
                onChangeAmount.invoke(textFieldValue.text)
            }
        },
        textStyle = ColoredTextStyle(
            color = textColor,
            textStyle = ComposeAppTheme.typography.headline1,
            textAlign = TextAlign.Start
        ),
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
        decorationBox = { innerTextField ->
            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.CenterStart
            ) {
                if (textState.text.isEmpty()) {
                    Text(
                        modifier = Modifier.fillMaxWidth(),
                        text = state.primaryPrefix ?: "0",
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 1,
                        color = ComposeAppTheme.colors.grey,
                        style = ComposeAppTheme.typography.headline1,
                        textAlign = TextAlign.Start
                    )
                }
                innerTextField()
            }
        }
    )

内容的提问来源于stack exchange,提问作者Rafael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 01:43:22