我正在使用java Prettify在Android应用中突出显示java代码的语法。我按照这个例子 Android Syntax Highlighting?
public class PrettifyHighlighter {
private static final Map<String, String> COLORS = buildColorsMap();
private static final String FONT_PATTERN = "<font color=\"#%s\">%s</font>";
private final Parser parser = new PrettifyParser();
public String highlight(String fileExtension, String sourceCode) {
StringBuilder highlighted = new StringBuilder();
List<ParseResult> 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<String, String> buildColorsMap() {
Map<String, String> map = new HashMap<>();
map.put("typ", "000000"); // black
map.put("kwd", "760098"); // violet
map.put("lit", "001ab7"); // dark blue
map.put("com", "999999"); // grey, comments
map.put("str", "ff4500"); // dark orange
map.put("pun", "333333"); // 90% black
map.put("pln", "156f15"); // dark green
return map;
}
}
并在textview中将其用作
PrettifyHighlighter highlighter = new PrettifyHighlighter();
String code="public class Example { \n" +
"public static void main(String args[]) { \n" +
" for(int i=1; i<=5; i++){ \n" +
" if(i==3){ \n" +
" break; \n" +
" } \n" +
" System.out.println(i); \n" +
" } \n" +
"} \n" +
"} ";
String highlighted = highlighter.highlight("java", code);
textView.setText(Html.fromHtml(highlighted.replace("\n","<br/>"),Html.FROM_HTML_MODE_COMPACT));
XML
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/ivImage3"
android:layout_alignStart="@+id/ivImage3"
android:layout_below="@+id/ivImage3"
android:scrollbars = "vertical"
android:layout_marginTop="@dimen/program_margin_top"
android:background="@drawable/textlines"
android:textSize="16dp"
android:text="" />
正如您所看到的那样&lt; =从输出中丢失,它只是显示 i5而不是i&lt; = 5
&lt;&lt;在textview中没有显示,我怎么能显示&lt;在语法中突出显示texview? 任何帮助表示赞赏
答案 0 :(得分:0)
试试这个
< for <
> for >
& for &
希望这有助于在XML文件中显示转义字符。