簡單的WebView自適應並巢狀在ScrollView裡
阿新 • • 發佈:2019-02-03
因為某種原因,我們總是需要展示一些複雜的文字,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常見問題