问题
I had to display some source code in my text view along with syntax highlighting So i used java prettify jar and imported it into my project and craeted a prettify highlighter class The highlighting works fine but there is no new line inserted between the code
Like this
My code
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));
}
}
prettifyhighlighter class
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;
}
}
tried using the following but nothing worked
/ n <br > <br \> , <![CDATA[ ... ]]>
this is how i tried
<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>
What shall i do Help me Thanks in advance
来源:https://stackoverflow.com/questions/35535105/syntax-highlighting-textview-displaying-source-code-not-putting-a-new-line