如何防止用户在开始时输入多个点和任何点



我想防止用户写多个点";并阻止他写一个"点"。

et_cm.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (et_cm.hasFocus()) {
if(et_cm.text.isEmpty()){
et_inches.setText("0")
}else{
val inch = ConvertCmToInch(et_cm.text.toString().toDouble()).toString()
et_inches.setText(inch)
}
}
}
override fun afterTextChanged(s: Editable) {}
})
<EditText
android:id="@+id/et_cm"
android:layout_width="113dp"
android:layout_height="48dp"
android:digits="1234567890."
android:ems="10"
android:hint="@string/cm"
android:inputType="numberDecimal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.677"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.415" />

我试着在if中添加这个,但是当我测试它时应用程序崩溃了:

et_cm.text.isEmpty() || et_cm.text.equals("^\.")

将强制文本的代码放在afterTextChanged中。如果您不仔细检查哪个特定字符从哪个特定的先前字符更改,则使用起来更简单。您还可以将现有代码移到这个函数中,我在下面的示例中就是这样做的。我还简化了你的代码。

只有当你真正修改了文本时才设置修改后的文本,否则会产生一个无限循环。

这段代码还试图保留光标的位置。否则,当有变化时,它会跳到开始。我没有费心使它足够复杂,以正确地保存它,以应对每一个可能的变化。

它使用while循环而不是if来检查点,因为用户可能正在粘贴包含多个不需要的字符的文本。你也可以使用Regex来做到这一点,但我认为这会使保持光标位置变得更加困难,如果有的话,它会失去CharSequence中的格式,尽管这通常不是用户输入文本的问题。

override fun afterTextChanged(s: Editable) {
var outS = s
var removedChars = 0
val cursorPosition = etCm.selectionStart
while (outS.startsWith('.')) {
outS = outS.delete(0, 1)
removedChars++
}
while (outS.count { it == '.' } > 1) {
val index = outS.lastIndexOf('.')
outS = outS.delete(index, index + 1)
removedChars++
}
if (s != outS) {
etCm.text = outS
etCm.setSelection(cursorPosition - removedChars)
} else if (etCm.hasFocus()) {
etInches.text = ConvertCmToInch(s.toString().toDoubleOrNull() ?: 0.0).toString()
}
}

相关内容

最新更新