How to get colored text in Android without using SpannableStringBuilder?

Viewed 154

I'm trying to make a fast Android code editor. Currently, this is the approach I'm taking:

  • Tokenize the source code
  • Assign different colors to spans of text, based on the type of the tokens
  • Call SpannableStringBuilder.setSpan(new ForegroundColorSpan(color)) for each of those colors

As you can imagine, for large files (1000 lines+) I'm attaching tens of thousands of spans. I noticed that when I edit large files, the app freezes for 2+ seconds when I try to delete a single character. I tracked it down to SpannableStringBuilder.replace doing a lot of work behind-the-scenes: https://github.com/aosp-mirror/platform_frameworks_base/blob/e72b6f0d3113c84df6d9113609942ef5d9b4e34e/core/java/android/text/SpannableStringBuilder.java

This method calls change and restoreInvariants, both of which have loops like this:

for (int i = 1; i < mSpanCount; i++) {
    ...
}

mSpanCount is typically around 20000 for 1000-line files, so these loops are extremely costly.

Is there a way to get colored text in Android without use of SpannableStringBuilder? I'm willing to deal with lower-level solutions that involve the C++ side of Android, or require me to stitch some things together.

0 Answers
Related