0

I have some performance problems with large amounts of spans in an EditText. Actually I'm syntaxhighligthing big source code. To highlight I set the spans with different color and different position. Assume we have the following:

public static void main(String[] args)

My code will output the following tokens (these are just numbers for the example, they could be wrong):

("Keyword", 0, 5) -> public

("Keyword", 7, 12) -> static

("Keyword", 14, 17) -> void

("Type", 24, 29) -> String

and then I set the spans:

for(Lexer.Token t: tokens) {
    text.setSpan(new ForegroundColorSpan(colorizer.getColor(t)), t.start, t.end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}

Now, assume that I add the char a at the beginning:

a public static void main(String[] args)

What happens is that all the spans need to be recalculated by adding 2. The problem is that if I have a huge file and so lots of spans, the calculation is slow.

My Idea was to apply the syntaxhighlight only to the visible part of the code, but it's a bit messy to do and I'm searching for a better and easier solution. Has someone a good solution for that?

Thank you in advance

Harsh Dattani
  • 2,109
  • 1
  • 17
  • 27
Christopher A
  • 153
  • 1
  • 10
  • what do you mean by **visible part of the code**? – Rajen Raiyarela Apr 30 '15 at 09:28
  • The one that is visible in the viewport. – Christopher A Apr 30 '15 at 09:35
  • There is no other way to add spans than what you do. What you can do better is use StringBuilder instead of String because String being immutable will be created everytime you perform operation on it (concatenation, toUpperCase, etc) consuming a lot of heap memory. – inmyth Apr 30 '15 at 09:37
  • Ok, thank you. So probably I have to follow my idea. Btw I was reading this post: [link](http://stackoverflow.com/questions/21496140/most-efficient-way-for-dynamic-text-color-change-in-textview) But I don't think that this is a solution for my case – Christopher A Apr 30 '15 at 09:41
  • Yes. And I don't know how any other way will speed up your calculation because there is no calculation in your code. You are passing Token which already has the start and end positions of the word. At first I thought you were adding Strings from your main method. If you have the full text and its tokens then you can just do something like http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android with loop to add spans. – inmyth Apr 30 '15 at 09:54
  • Thank you for the reply, but that's what I'm doing and the problem is not when setting the spans, but when updating them – Christopher A Apr 30 '15 at 10:06

0 Answers0