Android Development: Efficient Syntax Highlighting Tips?
I've developed my own syntax highlighting library for Android, and it works great,开发者_StackOverflow中文版 but the problem is it slows down the typing.
I've tried using an AsyncTask to perform the regular expressions in the background then apply the necassary colours but it still slowed down the typing process.
Currently, it reads the whole EditText, I thought of instead getting the line the text cursor is on, getting that lines CharSequence then performing the regular expressions on that line instead of the whole document, but I really don't know how I could get the line the user is working on :(.
Unless you're only doing single-line regexn/highlighting, your proposed strategy may not work. For example, you probably can't tell if you're in a multi-line comment without, well, scanning multiple lines. :-)
If you have not done so already, use Traceview to identify where the slowdowns are specifically. It may be that you can optimize enough other things. For example, maybe you're compiling all your Pattern
objects on the fly rather than defining them statically.
Beyond that, I think a typical pattern is to only apply syntax highlighting when the user pauses. One possible way of implementing that would be:
Step #1: On every text change (which you have presumably already hooked into), postDelayed()
a Runnable
and save the timestamp retrieved from SystemClock.uptimeMillis()
in a data member of your EditText
subclass (or wherever you have the syntax coloring logic). For the purposes of this answer, I'll call your delay period that you use with postDelayed()
as DELAY
.
Step #2: The Runnable
compares the current time from SystemClock.uptimeMillis()
with the time of the last text change. If the time difference is less than DELAY
, you know the user typed something in between when this Runnable
was scheduled and now, so you just do nothing. If the time difference >= DELAY
, though, you run through your syntax coloring logic.
This way, you skip applying the syntax coloring until the user pauses, thereby not interrupting their typing. You can tweak DELAY
, or perhaps make it configurable.
BTW, you are planning on releasing this as an open source library, right? :-)
精彩评论