Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I managed to create a syntax highlighter for Android, based on the <a href="https://code.google.com/p/google-code-prettify/" rel="noreferrer">Prettify</a>. It was easy, actually, when I found the <a href="https://code.google.com/p/java-prettify/" rel="noreferrer">Java Prettify</a>. Just download it (sadly, it is not published for maven) and add its jar to the build path of you application.</p> <p>The syntax highlighter I created based on it:</p> <pre><code>public class PrettifyHighlighter { private static final Map&lt;String, String&gt; COLORS = buildColorsMap(); private static final String FONT_PATTERN = "&lt;font color=\"#%s\"&gt;%s&lt;/font&gt;"; private final Parser parser = new PrettifyParser(); public String highlight(String fileExtension, String sourceCode) { StringBuilder highlighted = new StringBuilder(); List&lt;ParseResult&gt; results = parser.parse(fileExtension, sourceCode); for(ParseResult result : results){ String type = result.getStyleKeys().get(0); String content = sourceCode.substring(result.getOffset(), result.getOffset() + result.getLength()); highlighted.append(String.format(FONT_PATTERN, getColor(type), content)); } return highlighted.toString(); } private String getColor(String type){ return COLORS.containsKey(type) ? COLORS.get(type) : COLORS.get("pln"); } private static Map&lt;String, String&gt; buildColorsMap() { Map&lt;String, String&gt; map = new HashMap&lt;&gt;(); map.put("typ", "87cefa"); map.put("kwd", "00ff00"); map.put("lit", "ffff00"); map.put("com", "999999"); map.put("str", "ff4500"); map.put("pun", "eeeeee"); map.put("pln", "ffffff"); return map; } } </code></pre> <p>The colors of the syntax are hardcoded, but may be also set by i.e. application preferences. In order to display a <em>Java</em> source code in a <code>TextView</code>, just do:</p> <pre><code>// code is a String with source code to highlight // myTextView is a TextView component PrettifyHighlighter highlighter = new PrettifyHighlighter(); String highlighted = highlighter.highlight("java", code); myTextView.setText(Html.fromHtml(highlighted)); </code></pre> <p>The Java Prettify library made my application around 50kB bigger.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload