不一致的 onTextChanged() 行为

Inconsistent onTextChanged() behaviour

我写了下面的代码来弄清楚 onTextChanged() 方法是如何工作的:

override fun onTextChanged(string: CharSequence?, start: Int, before: Int, count: Int) {
                Log.d(TAG, "onTextChanged triggered.")
                Log.d(TAG, "string = $string")
                Log.d(TAG, "start = $start")
                Log.d(TAG, "before = $before")
                Log.d(TAG, "count = $count")
                Log.d(TAG, "____________________________________________________________")

这是我注意到的:当我只输入字母时,计数非常简单:

onTextChanged triggered.
string = a
start = 0
before = 0
count = 1
____________________________________________________________
onTextChanged triggered.
string = aa
start = 0
before = 1
count = 2
____________________________________________________________
onTextChanged triggered.
string = aaa
start = 0
before = 2
count = 3
____________________________________________________________
onTextChanged triggered.
string = aaaa
start = 0
before = 3
count = 4
____________________________________________________________
onTextChanged triggered.
string = aaaaa
start = 0
before = 4
count = 5
____________________________________________________________

现在,如果我添加 3 个(或更多)数字,然后继续输入字母,就会发生以下情况:

onTextChanged triggered.
string = aaaaa2
start = 0
before = 5
count = 6
____________________________________________________________
onTextChanged triggered.
string = aaaaa22
start = 0
before = 6
count = 7
____________________________________________________________
onTextChanged triggered.
string = aaaaa222
start = 0
before = 7     
count = 8
____________________________________________________________
onTextChanged triggered.
string = aaaaa222
start = 0
before = **8**      <---- This is when it gets funny
count = **8**
____________________________________________________________
onTextChanged triggered.
string = aaaaa222a
start = 8
before = 0
count = 1
____________________________________________________________
onTextChanged triggered.
string = aaaaa222aa
start = 9
before = 0
count = 1
 ____________________________________________________________
onTextChanged triggered.
string = aaaaa222aaa
start = 10
before = 0
count = 1
____________________________________________________________
onTextChanged triggered.
string = aaaaa222aaaa
start = 11
before = 0
count = 1
____________________________________________________________
onTextChanged triggered.
string = aaaaa222aaaaa
start = 12
before = 0
count = 1
____________________________________________________________

对我来说,似乎输入 3 位数字会以某种方式改变 TextWatcher 的行为,使其将后面的所有内容视为 Char 而不是 CharSequence。

对这种行为有解释吗?

虽然我没有解释为什么它会发生在 3 位数字上,但我发现根本无法保证偏移量何时会失效。检查这个 this

“您不会被告知更改发生在何处,因为其他 afterTextChanged() 方法可能已经进行了其他更改并且 使偏移量无效 。但是如果您需要在此处了解,你可以在onTextChanged(CharSequence, int, int, int)中使用Spannable#setSpan来标记你的位置,然后从这里开始查找跨度结束的地方。"

TextWatcher 的一个可能实现是 this one。 这样你就会有正确的开始和结束索引。