webview展示本地的HTML文件来显示Markdown

本文介绍了在Android中展示Markdown格式文本的两种方法。一种是使用MarkdownView库,直接加载markdown文本;另一种是借助js库marked.js,将Markdown转换为HTML并加载到WebView。对于动态内容,需要使用JavaScriptInterface来实现与服务器的交互。

起因: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![替代文字](https://wt-prj.oss.aliyuncs.com/1c9327bc704581/2e8b76ed-2f8a-41be-9835-3902f550460e.png)\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 



评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值