如何在 android 中突出显示代码片段?
how to highlight code snippet in android?
我正在编写一个包含一些代码片段的应用程序。
作为通常的方式,它可以在 TextView 中显示,但我想突出显示一些关键字,例如 "main" 、 "int" 、 "class"、"return" 等。
很多时间后,我发现可以使用 html 和 css 加载到 webview 上来完成,但它有一些缺点,如渲染速度慢,因此会导致糟糕的用户体验。
是否有更好的方法来解决问题?
给我一些代码示例会很棒...
谢谢
使用 SpannableString:
SpannableString string = new SpannableString("Your text that has to be highlighted");
string.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 10, 0);
textView.setText(string);
BackgroundColorSpan 更改背景颜色。另请查看 ForegroundColorSpan。
或使用接受 Html 标签的 Html.fromHtml
:
String text1 = "Start your text ";
String text2 = "<font color='#EE0000'>and it is now red</font>";
textView.setText(Html.fromHtml(text1 + text2));
Html 方式可能比 SpannableString 慢一点,因为它涉及解析字符串。
我正在编写一个包含一些代码片段的应用程序。
作为通常的方式,它可以在 TextView 中显示,但我想突出显示一些关键字,例如 "main" 、 "int" 、 "class"、"return" 等。 很多时间后,我发现可以使用 html 和 css 加载到 webview 上来完成,但它有一些缺点,如渲染速度慢,因此会导致糟糕的用户体验。
是否有更好的方法来解决问题? 给我一些代码示例会很棒...
谢谢
使用 SpannableString:
SpannableString string = new SpannableString("Your text that has to be highlighted");
string.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 10, 0);
textView.setText(string);
BackgroundColorSpan 更改背景颜色。另请查看 ForegroundColorSpan。
或使用接受 Html 标签的 Html.fromHtml
:
String text1 = "Start your text ";
String text2 = "<font color='#EE0000'>and it is now red</font>";
textView.setText(Html.fromHtml(text1 + text2));
Html 方式可能比 SpannableString 慢一点,因为它涉及解析字符串。