我必须在文本视图中显示一些源代码以及语法高亮显示 所以我使用了java prettify jar并将其导入我的项目并且开始了一个美化的荧光笔课程 突出显示工作正常,但代码之间没有插入新行
喜欢这个
我的代码
的strings.xml
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">syntaxtest</string>
<string name="javacode">
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.mainTextView);
}
}</string>
mainactivity.java
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String code = getResources().getString(R.string.javacode);
TextView tv = (TextView) findViewById(R.id.mainTextView);
// code is a String with source code to highlight
// myTextView is a TextView component
PrettifyHighlighter highlighter = new PrettifyHighlighter();
String highlighted = highlighter.highlight("java", code);
tv.setText(Html.fromHtml(highlighted));
}
}
美化高级课程
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", "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;
}
}
尝试使用以下内容但没有任何效果
/ n <br > <br \> , <![CDATA[ ... ]]>
这是我尝试的方式
<string name="javacode">
<![CDATA[
super.onCreate(savedInstanceState);<br \>
setContentView(R.layout.main);<br>
String code = getResources().getString(R.string.javacode);<br />
<br />
TextView tv = (TextView) findViewById(R.id.mainTextView);<br />
]]>
</string>
我该怎么办? 帮我 提前致谢