kotlin Jetpack只构成视觉转换数

bvjxkvbb  于 2022-11-25  发布在  Kotlin
关注(0)|答案(1)|浏览(85)

如何实现一个只有digits和一个'.'的可视转换。这就是我尝试实现的方法,但得到偏移错误:

class NumberTransformer : VisualTransformation {

override fun filter(text: AnnotatedString): TransformedText {

    var out = ""
    var dotCount = text.count { it == '.' }
    text.forEach {
        if (it.isDigit())
            out += it.toString().convertToEnglish()
        if (it == '.' && dotCount == 0)  {
            dotCount++
            out += it
        }
    }

    val numberOffsetTranslator = object : OffsetMapping {
        override fun originalToTransformed(offset: Int): Int {
            return offset - dotCount
        }

        override fun transformedToOriginal(offset: Int): Int {
            return offset + dotCount
        }
    }

    return TransformedText(
        text = AnnotatedString(out),
        offsetMapping = numberOffsetTranslator
    )
}
}
rkkpypqq

rkkpypqq1#

在这种情况下,最好使用onValueChange参数,通过正则表达式模式限制允许的字符。
类似于:

val pattern = remember { Regex("^\\d*\\.?\\d*\$") }

TextField(
    value = text,
    onValueChange = {
        if (it.isEmpty() || it.matches(pattern)) {
            text = it
        }
    },
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)

相关问题