我想创建这样的文本字段:
怎么做,文本字段背景?
您可以使用 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)
}