Stack Overflow archive
1 scoreaccepted

Multiple ForegroundColorSpan on Editable issue on Android 6.0+

score
1
question views
549
license
CC BY-SA 3.0

If I remove all spans before setting the new ForegroundColorSpan then I get the desired behavior. Unfortunately, this is a lot more work if an EditText has a lot of text.

What I did for a fix:

java
@Override public void afterTextChanged(Editable editable) {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    // remove old spans before highlighting
    // this does not work on Android 6.0+
    ForegroundColorSpan[] spans = editable.getSpans(0, editable.length(), ForegroundColorSpan.class);
    for (ForegroundColorSpan span : spans) {
      editable.removeSpan(span);
    }
  }

  for (int i = 0; i < patterns.length; i++) {
    Pattern p = patterns[i];
    Matcher m = p.matcher(editable);
    while (m.find()) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Remove any spans in the given range.
        ForegroundColorSpan[] oldspans = editable.getSpans(m.start(), m.end(), ForegroundColorSpan.class);
        for (ForegroundColorSpan span : oldspans) {
          editable.removeSpan(span);
        }
      }
      editable.setSpan(new ForegroundColorSpan(colors[i]), m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
  }
}

I'm not sure what changed in Android 6.0+ and if anyone has any insight it would be much appreciated.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.