1

I am learning how to make a syntax highlighter. What I would like to ask is how I can change the text color of some part of the text and leave the rest in default color ?

What I mean is doing something similar to what most IDEs do; they highlight they keywords and let the others be in black color.

How can this be done in Android EditText, or some other view?

An SO User
  • 24,612
  • 35
  • 133
  • 221
  • Answer here: http://stackoverflow.com/questions/4897349/android-coloring-part-of-a-string-using-textview-settext – live-love Oct 28 '14 at 17:42

3 Answers3

3

If you want to make the 'EditText' behave like an IDE (i.e. eclipse) then you need to define a list of words that you want to be in different color then add a function like this:

EditText et = new  EditText(mContext);
et.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
});

Then use the 'spanable' class to color your key words:

Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
et.setText(wordtoSpan);

You will need to implement some logic to find the starting and ending index of your key words and then iterate over the string to set the color of each item you want.

funerr
  • 7,212
  • 14
  • 81
  • 129
Ali Imran
  • 8,927
  • 3
  • 39
  • 50
  • `yes you need to implement some logic to find the starting and ending index of your key words` well I know a third party library that does that :) – An SO User Aug 27 '13 at 10:14
2

You can use html form like this.

textView..setText(Html.fromHtml("<font size="5">Here is a size 5 font</font>"));
textView..setText(Html.fromHtml("<font color="#990000">This text is hex color #990000</font>
<br />"));
KEYSAN
  • 885
  • 8
  • 23
1

Check SpannbleStringBuilder.

More details: Android: Coloring part of a string using TextView.setText()?

Community
  • 1
  • 1
akuzma
  • 1,592
  • 6
  • 22
  • 49