gpt4 book ai didi

android - 如何在jetpack compose中创建带有掩码的文本字段输入?

转载 作者:行者123 更新时间:2023-12-04 23:46:23 26 4
gpt4 key购买 nike

我需要在 jetpack compose 中使用这样的掩码的文本字段:NNNNN-NNN其中 N 是从 0 到 9 的整数。我需要我的可组合函数在 OutlinedTextField 中有这个掩码:

@Composable
private fun EditTextField(
labelText: String,
value: String,
keyboardType: KeyboardType = KeyboardType.Text,
onValueChanged: (String) -> Unit
) {
OutlinedTextField(
modifier = Modifier.padding(top = 8.dp),
label = { Text(text = labelText) },
keyboardOptions = KeyboardOptions(keyboardType = keyboardType),
value = value,
onValueChange = onValueChanged
)
}

最佳答案

您可以使用 visualTransformation属性(property):

OutlinedTextField(
value = text,
onValueChange = { it ->
text = it.filter { it.isDigit() }
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
visualTransformation = MaskTransformation()
)
和:
class MaskTransformation() : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
return maskFilter(text)
}
}


fun maskFilter(text: AnnotatedString): TransformedText {

// NNNNN-NNN
val trimmed = if (text.text.length >= 8) text.text.substring(0..7) else text.text
var out = ""
for (i in trimmed.indices) {
out += trimmed[i]
if (i==4) out += "-"
}

val numberOffsetTranslator = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset <= 4) return offset
if (offset <= 8) return offset +1
return 9

}

override fun transformedToOriginal(offset: Int): Int {
if (offset <=5) return offset
if (offset <=9) return offset -1
return 8
}
}

return TransformedText(AnnotatedString(out), numberOffsetTranslator)
}
enter image description here

关于android - 如何在jetpack compose中创建带有掩码的文本字段输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69064137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com