我有一个文本字段,其中不能超过 10 个字符,并且要求用户以“mm/dd/yyyy”格式输入日期。每当用户键入前 2 个字符时,我都会附加“/”,当用户键入接下来的 2 个字符时,我会再次附加“/”。
为了实现这一目标,我做了以下操作:
var maxCharDate = 10
TextField(
value = query2,
onValueChange = {
if (it.text.length <= maxCharDate) {
if (it.text.length == 2 || it.text.length == 5)
query2 = TextFieldValue(it.text + "/", selection = TextRange(it.text.length+1))
else
query2 = it
}
emailErrorVisible.value = false
},
label = {
Text(
"Date of Birth (mm/dd/yyyy)",
color = colorResource(id = R.color.bright_green),
fontFamily = FontFamily(Font(R.font.poppins_regular)),
fontSize = with(LocalDensity.current) { dimensionResource(id = R.dimen._12ssp).toSp() })
},
.
.
.
Run Code Online (Sandbox Code Playgroud)
它正在工作,只是附加的“/”在按退格键时不会被删除,而其他字符会被删除。
如何使按退格键时“/”也被删除?
android textfield android-jetpack-compose android-compose-textfield