起因:Android 显示markdown格式文本。
要显示markdown,思路是把markdown格式转换成html标签格式。
1.使用MarkdownView
这个库里的MarkdownView 本身就是继承自WebView。
直接调用该view的loadMarkdown(“markdown格式的文本”);方法。
该方法中的
MarkdownProcessor m = new MarkdownProcessor();
String html = m.markdown(txt);就是将markdown格式转换成html标签格式
这种方法存在的问题:
1.表格无法显示
2.该换行的时候没有换行
然后使用了另一个<markdown格式转换成html标签格式>的lib markdown4j-2.2.jar
将
html = new Markdown4jProcessor().process(txt);
替换
MarkdownProcessor m = new MarkdownProcessor();
String html = m.markdown(txt);表格还是无法优雅显示(单元格无边框,以|分割),但是可以换行了。
其实此处直接使用WebView来加载转换后的html格式的字符串就可以了。
2.使用js库<把markdown格式转换成html标签格式> 传送门
重要的文件是 marked.js,下载下来放在assets文件夹中,再在assets中新建一个html文件
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Marked in the browser</title>
<script src="marked.js"></script>
</head>
<body>
<div id="content"></div>
<script>
document.getElementById('content').innerHTML =
marked('最期待功能前10名\n\n\n**通知提醒:10票**\n\n* 通知按主题聚合\n*',{breaks: true});
</script>
</body>
</html>
其中的{breaks:true} 是因为:标准的markdown语法\n\n是换行,而此处想让\n就换行,加上这个属性就可以做到\n换行。
在Activity中使用:
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webView.loadUrl(url);
这种方法只能显示固定的内容。
要想显示从服务器上获取的内容webView 需要增加 JavaScriptInterface
<pre name="code" class="java">webView.<span style="font-family: Arial, Helvetica, sans-serif;">addJavascriptInterface(new JsInterface("markdown 格式的文本"), "JsInterface");</span>
JsInterface类的代码:
import android.webkit.JavascriptInterface;
public class JsInterface {
private String content;
public JsInterface(String content) {
this.content = content;
}
@JavascriptInterface
public String getContent() {
return content;
}
}
在html文件中:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Marked in the browser</title>
<script src="marked.js"></script>
</head>
<body>
<div id="content"></div>
<script>
var html = JsInterface.getContent();
document.getElementById('content').innerHTML =marked(html,{breaks: true});
</script>
</body>
</html>
推荐给大家翻墙工具红杏 http://honx.in/i/U6lVvYKo1zb9vb1L
本文介绍了在Android中展示Markdown格式文本的两种方法。一种是使用MarkdownView库,直接加载markdown文本;另一种是借助js库marked.js,将Markdown转换为HTML并加载到WebView。对于动态内容,需要使用JavaScriptInterface来实现与服务器的交互。
1411

被折叠的 条评论
为什么被折叠?



