Android Edittext- Clearing Spans
Asked Answered
C

3

22

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!

Cum answered 22/2, 2012 at 21:10 Comment(0)
A
43

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]);
Arapaima answered 23/4, 2012 at 0:30 Comment(2)
Thanks Andre. Actually I had managed to solve it before (sorry I just forgot to answer it myself!), but thanks for posting the answer- I am sure someone else will benefit from it.Cum
If you do a editable.getSpans(0, editable.length(), Object.class); you can see it picks up a lot of things. If you manually remove all of these you get the same result as clearSpans. Not sure what the use case for clearSpans would be since it messes things up pretty bad.Blocker
B
5
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.

Blocker answered 8/11, 2018 at 12:5 Comment(0)
M
-1

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)
Moonmoonbeam answered 4/6, 2019 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.