how to highlight code snippet in android?


i’m writing an application which consists some code snippets.

as the usual manner it can be displayed in TextView but i want to highlight some keywords say “main” , “int” , “class”, “return” , etc.
after lots of time i figured out it can be done using html and css that loads to webview up , but it has some disadvantages like slow rendering so it makes bad user Experience .

is there a better way to approach the solution ?
it would be great to give me some code example…



Use SpannableString:

SpannableString string = new SpannableString("Your text that has to be highlighted");
string.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 10, 0);

BackgroundColorSpan changes the background color. Also check out ForegroundColorSpan.

Or use Html.fromHtml which accepts Html tags:

String text1 = "Start your text ";
String text2 = "<font color='#EE0000'>and it is now red</font>";
textView.setText(Html.fromHtml(text1 + text2));

Html way might be a bit slower than SpannableString as it involves parsing the string.

Answered By – Bob

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.