Stack Overflow archive
8 score

Syntax highlighting on android EditText using Span?

score
8
question views
3.6K
license
CC BY-SA 3.0

Using string.indexOf(s) will get the first occurrence. Instead of having a map of keywords and using indexOf you could use a regular expression. I wrote this up real quick as an example:

Screenshot of example EditText below:

enter image description here

Example:

js
final EditText editText = new EditText(this);
editText.addTextChangedListener(new TextWatcher() {

  ColorScheme keywords = new ColorScheme(
      Pattern.compile(
          "\\b(package|transient|strictfp|void|char|short|int|long|double|float|const|static|volatile|byte|boolean|class|interface|native|private|protected|public|final|abstract|synchronized|enum|instanceof|assert|if|else|switch|case|default|break|goto|return|for|while|do|continue|new|throw|throws|try|catch|finally|this|super|extends|implements|import|true|false|null)\\b"),
      Color.CYAN
  );

  ColorScheme numbers = new ColorScheme(
      Pattern.compile("(\\b(\\d*[.]?\\d+)\\b)"),
      Color.BLUE
  );

  final ColorScheme[] schemes = { keywords, numbers };

  @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

  }

  @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

  }

  @Override public void afterTextChanged(Editable s) {
    removeSpans(s, ForegroundColorSpan.class);
    for (ColorScheme scheme : schemes) {
      for(Matcher m = scheme.pattern.matcher(s); m.find();) {
        s.setSpan(new ForegroundColorSpan(scheme.color),
            m.start(),
            m.end(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      }
    }
  }

  void removeSpans(Editable e, Class<? extends CharacterStyle> type) {
    CharacterStyle[] spans = e.getSpans(0, e.length(), type);
    for (CharacterStyle span : spans) {
      e.removeSpan(span);
    }
  }

  class ColorScheme {
    final Pattern pattern;
    final int color;

     ColorScheme(Pattern pattern, int color) {
      this.pattern = pattern;
      this.color = color;
    }
  }

});

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