Android Edittext- Clearing Spans

2020-05-31 22:47发布

I am trying to get an EditText to clear its spans by calling EditText.getText().clearSpans(). However, if I call this method, the EditText starts to behave strangely, with line feeds appearing as boxes and any spans I then set being in completely the wrong place.

So my question is: How do I clear spans from and EditText? (Without calling setText()- the text may be thousands of lines long and its too slow to redraw it all frequently)

Thanks very much!

3条回答
成全新的幸福
2楼-- · 2020-05-31 23:08

the best answer would be this which "s" is the string that you want to show instead of spans or it can be empty String.

the code is in Kotlin

editText.setText(s)
editText.setSelection(editText.text.length)
查看更多
冷血范
3楼-- · 2020-05-31 23:12
private void clearSpans(@NonNull final Editable editable) {
    final Object[] spans = editable.getSpans(0, editable.length(), Object.class);
    for (final Object span : spans) {
        if (span instanceof ForegroundColorSpan || span instanceof SpannableTextView.CustomTypefaceSpan) {
            editable.removeSpan(span);
        }
    }
}

Depending on type of spans you have added you may have to include more than just ForegroundColorSpan. The above method is a simple drop in replacement and it easy to specify what spans to remove.

查看更多
看我几分像从前
4楼-- · 2020-05-31 23:20

Had the same problem. Solved it by removing only the types of spans that I added to the EditText. I guess clearSpans removes more than it should. I did something like this for each type of span I used:

toRemoveSpans = et.getSpans(0, et.getText().length(), ForegroundColorSpan.class);
for (int i = 0; i < toRemoveSpans.length; i++) 
    et.removeSpan(toRemoveSpans[i]);
查看更多
登录 后发表回答