WebView-合理的用法(避免文字亂碼+文字大小適配)(一)

----  從本地加載+圖片寬高自適應屏幕

  //設置自適應屏幕,兩者合用
        settings.setUseWideViewPort(true); //將圖片調整到適合webview的大小
        settings.setLoadWithOverviewMode(true); // 縮放至屏幕的大小
        webView.loadDataWithBaseURL(null, htmlContent, "text/html", "utf-8", null);
如果使用loadData(htmlContent,"text/html","utf-8");會出現文字亂碼,

webView.loadData(htmlContent, "text/html", "utf-8");

----  指定字體大小

 int fontSize = (int) getResources().getDimension(R.dimen.y28);
        Log.i(TAG, "initView: fontSize = " + fontSize);
        settings.setDefaultFontSize(fontSize);


---- 最好的適配方案是在Html5源代碼中把樣式配好。


----WebView比Browser功能要弱,核心目的是展示頁面,官方介紹

It does not include any features of a fully developed web browser, such as navigation controls or an address bar.
 All that WebView does, by default, is show a web page.

==================

-----  一個成功的案例,依據 Html5 內容,藉助css樣式實現是適配,只用css即可,不需要webview的任何setting

 String origianlHtmlStr = result.getData().getContentList();
     
        String cssLayout = "<style>*{padding: 0;margin: 0}#webview_content_wrapper{margin: 10px 15px 0 15px;}
         p{color: #333333;line-height: 2em;font-size:14px;opacity: 1;}
         img {margin-top: 13px;margin-bottom: 15px;width: 100%;}</style>";
        String htmlModify = origianlHtmlStr.replaceAll("<br/>", "");
        String htmlcontent = cssLayout + "<body><div id='webview_content_wrapper'>" + htmlModify + "</div></body>";
        webView.loadDataWithBaseURL(null, htmlcontent, "text/html", "UTF-8", null);

------ origin html str

<p><span style="">華春瑩在當天舉行的外交部例行記者會上對《環球時報》記者表示,中方一直在關注日本福島核泄漏極其後續影響。
“我注意到在福島核事故發生六週年之際,日本國內媒體也在大量報道評論,總體認爲日本政府在污染水和土壤及放射性廢棄物處理方面缺乏有效手段,
向海洋排放核污水給周邊海洋環境和民衆健康帶來隱患,有關對策滯後且信息公開不透明,食品安全等相關數據缺乏足夠說服力。</span></p>
<div class="image-package"><img src="http://duty.oss-cn-shenzhen.aliyuncs.com/8380e6fa-db21-4b7c-83e1-34bff9ba89a0tyggh2.png" data-by-webuploader="true"/>
</div><p>表示,中方一直在關注日本福島核泄漏極其後續影響。“我注意到在福島核事故發生六週年之際,日本國內媒體也在大量報道評論,
總體認爲日本政府在污染水和土壤及放射性廢棄物處理方面缺乏有效手段,向海洋排放核污水給周邊海洋環境和民衆健康帶來隱患,
有關對策滯後且信息公開不透明,食品安全等相關數據缺乏足夠說服力。</p><div class="image-package">
<img src="http://duty.oss-cn-shenzhen.aliyuncs.com/b25eaee8-f133-4618-9411-94685f4ae2detyggh4.png" data-by-webuploader="true"/></div>
<div class="image-package"><img src="http://duty.oss-cn-shenzhen.aliyuncs.com/726d283c-8c8d-4e34-916b-52a78bca3ba0tyggh1.png" data-by-webuploader="true"/>
</div><p><span style=""></span><br/></p>

------- 之前添加了以下的setting+以上css適配導致錯誤

 settings.setUseWideViewPort(true); //將圖片調整到適合webview的大小
  settings.setLoadWithOverviewMode(true); // 縮放至屏幕的大小



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章