Android TextView 高亮编程语言关键字 - 无需 Github 依赖
要在 Android TextView 中高亮编程语言关键字,可以使用 Markdown 库。以下是一些步骤:
- 创建一个 TextView,并使用 Markdown 库将 markdown 文本转换为 SpannableString。例如:
TextView textView = findViewById(R.id.text_view);
String markdown = '```java\npublic class MainActivity {\n//code here\n}\n```';
AndDown converter = new AndDown();
String html = converter.markdownToHtml(markdown);
Spanned spanned = Html.fromHtml(html, new CodeBlockSpanner(), null);
textView.setText(spanned);
- 创建一个 CodeBlockSpanner 类,以自定义代码块的样式。例如:
private class CodeBlockSpanner implements Html.TagHandler {
private int start;
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equalsIgnoreCase('code')) {
if (opening) {
start = output.length();
} else {
String code = output.subSequence(start, output.length()).toString();
output.setSpan(new ForegroundColorSpan(Color.BLUE), start, output.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
}
- 在 CodeBlockSpanner 类中,可以使用正则表达式来识别和高亮关键字。例如:
private static final String[] KEYWORDS = { 'abstract', 'continue', 'for', 'new', 'switch', 'assert', 'default', 'goto', 'package', 'synchronized', 'boolean', 'do', 'if', 'private', 'this', 'break', 'double', 'implements', 'protected', 'throw', 'byte', 'else', 'import', 'public', 'throws', 'case', 'enum', 'instanceof', 'return', 'transient', 'catch', 'extends', 'int', 'short', 'try', 'char', 'final', 'interface', 'static', 'void', 'class', 'finally', 'long', 'strictfp', 'volatile', 'const', 'float', 'native', 'super', 'while' };
private class CodeBlockSpanner implements Html.TagHandler {
private int start;
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equalsIgnoreCase('code')) {
if (opening) {
start = output.length();
} else {
String code = output.subSequence(start, output.length()).toString();
Pattern pattern = Pattern.compile('\b(' + StringUtils.join(KEYWORDS, '|') + ')\b');
Matcher matcher = pattern.matcher(code);
while (matcher.find()) {
output.setSpan(new ForegroundColorSpan(Color.BLUE), start + matcher.start(), start + matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
}
}
这样,在 TextView 中显示的代码块将使用蓝色高亮显示编程语言关键字。
原文地址: https://www.cveoy.top/t/topic/mV1X 著作权归作者所有。请勿转载和采集!