3

我想创建这样的文本字段:

在此处输入图像描述

怎么做,文本字段背景?

4

1 回答 1

3

您可以使用 aTextField并使用属性格式化数字visualTransformation

TextField(value = text,
    onValueChange = { text = it },
    visualTransformation = NumberTransformation()
)

NumberTransformation类似的东西在哪里:

class NumberTransformation() : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        return numberFilter(text)
    }
}

fun numberFilter(text: AnnotatedString): TransformedText {

    // +XXX XXX XXX XXX
    val trimmed = if (text.text.length >= 12) text.text.substring(0..11) else text.text
    var out = ""
    for (i in trimmed.indices) {
        if (i==0) out += "+"
        out += trimmed[i]
        if (i % 3 == 2 && i != 11) out += " "
    }

    val numberOffsetTranslator = object : OffsetMapping {
        override fun originalToTransformed(offset: Int): Int {
            if (offset <= 0) return offset
            if (offset <= 2) return offset +1
            if (offset <= 5) return offset +2
            if (offset <= 8) return offset +3
            if (offset <= 12) return offset +4
            return 16
        }

        override fun transformedToOriginal(offset: Int): Int {
            if (offset <=0) return offset
            if (offset <=3) return offset -1
            if (offset <=7) return offset -2
            if (offset <=11) return offset -3
            if (offset <=15) return offset -4
            return 11
        }
    }

    return TransformedText(AnnotatedString(out), numberOffsetTranslator)
}

在此处输入图像描述

于 2021-05-10T16:50:21.030 回答