我有一个 EditText,用户可以在其中编写数学表达式,例如:
32423423+32423423+434234+3423423
如果它不适合屏幕,表达式会像这样中断:
32423423+32423423+43
4234+3423423
但是如何在每个最右边的 + 符号之后发生中断,如下所示:
32423423+32423423+
434234+3423423
有没有办法将EditText中的+定义为换行符?
为了实现此目的,您可以使用自定义 TextWatcher 在用户键入数学表达式时在 + 符号后自动插入换行符。以下是有关如何实施此操作的分步指南:
fun setupEditTextWithLineBreaks(editText: EditText) {
editText.addTextChangedListener(object : TextWatcher {
private var isUpdating = false
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
if (isUpdating) return
isUpdating = true
val originalText = s.toString()
val newText = addLineBreaksAfterPlus(originalText)
if (newText != originalText) {
editText.setText(newText)
editText.setSelection(newText.length)
}
isUpdating = false
}
private fun addLineBreaksAfterPlus(text: String): String {
// Insert line breaks after each '+' sign if not already followed by a newline
return text.replace("+", "+\n")
.replace("\n\n", "\n") // Avoid double line breaks
}
})
}