Android: EditText出现StackOverflowError异常

由于需要对EditText进行实时监听,所以注册了TextWatcher。但是在onTextChanged()中却抛出了StackOverflowError异常:

java.lang.StackOverflowError
at android.widget.TextView.invalidateCursor(TextView.java:4456)
at android.widget.TextView.spanChange(TextView.java:7546)
at android.widget.TextView$ChangeWatcher.onSpanChanged(TextView.java:9339)
at android.text.SpannableStringBuilder.sendSpanChanged(SpannableStringBuilder.java:999)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:658)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
at android.text.Selection.setSelection(Selection.java:76)
at android.text.Selection.setSelection(Selection.java:87)
at android.widget.EditText.setSelection(EditText.java:99)

起初认为 onTextChanged()中过度频繁调用setSelection()方法导致的,最后发现:原因在于onTextChanged()中又对EditText调用了setText()方法,由于setText()会再次触发onTextChanged(),最终导致无限递归调用,所以就抛出了StackOverflowError异常。

你可能感兴趣的:(Android: EditText出现StackOverflowError异常)