因為某種原因,我們總是需要展示一些復雜的文本,Html.fromHtml()已經不能滿足我們的需求,比如后臺可編輯的文本在前端顯示起來比較吃力,所以為了解決一些復雜的文本顯示就需要用到WebView。
WebView in ScrollView
我們都知道ScrollView和WebView都有滾動的效果,所以我們需要先屏蔽WebView的滾動事件。
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
中文亂碼
如果出現中文亂碼,你可以這樣設置
webView.loadData(body, "text/html; charset=utf-8", "utf-8");
Auto Scale
這時候如果后端如果傳過來的不是完整的Html,而是只有body部分的內容,那么我們就需要補充并添加一些css樣式來達到自適應的效果。
WebView webView = new WebView(this);
webView.setWebViewClient(new SimpleWebViewClient(title));
webView.getSettings().setDefaultTextEncodingName("utf-8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
} else {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
}
webView.loadData(getHtmlData(body), "text/html; charset=utf-8", "utf-8");
別忘了頭部的設定:
private String getHtmlData(String bodyHTML) {
String head = "<head>" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
"<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
"</head>";
return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
}
End
最后,原本還擔心如何控制WebView的高度,沒想到WebView可以自己適應內容最長的高度。再附上別人總結的WebView常見問題