這兩天用webview加載html時遇到很多問題也學到了不少,僅在這里記載以供以后參考,哪里不完善的還望有心人多加補充。

(這里只介紹webview.loadUrl())

思路:拿到網頁url,然后把網頁上的html寫到本地文件中,然后用?webview.loadUrl("file:///"+htmlpath)加載圖文。

webview是什么、?

注意:

1.寫到本地文件時的編碼要和加載本地文件時的編碼一樣,否則亂碼!

2.html文件里的字體要使用同一種字體,否則客戶端顯示出來用其他字體的文字會出現亂碼(這個可是我對照html文件好久才發現的哦)。

webview加載幾次就不顯示、?

以下是代碼塊:

//定義本地路徑
??htmlpath=?FileUtils.getSDPATH()+"common_page_content/"+p_w_picpathName+".html";

?

webview多標簽,?StringTool.StringSaveTofile(cpc.getContent(),?htmlpath);(cpc.getContent()是將要寫入本地文件的html網頁

//寫入本地文件的方法
?static?public?void?StringSaveTofile(String?theString?,String?savePath)?throws?IOException{
???ByteArrayInputStream?stream?=?new?ByteArrayInputStream(theString.getBytes("utf-8"));//這個編碼一定要和下面的一樣
??FileUtils.SaveFile(stream,?savePath);
???stream.close();
?}

?

public?static?void?SaveFile(InputStream?input,String?savePath)
?{

安卓webview加載本地html。??File?file?=?null;
??OutputStream?output?=?null;
??byte?buffer?[]?=?new?byte[4?*?1024];

??try?{
???file?=?creatSDFile(savePath);

???output?=?new?FileOutputStream(file);
???while((input.read(buffer))?!=?-1){
????output.write(buffer);
???}

???output.flush();

??}?catch?(Exception?e)?{
???//?TODO?Auto-generated?catch?block
???e.printStackTrace();
??}finally{
???try{
????output.close();
???}
???catch(Exception?e){
????e.printStackTrace();
???}
??}

?}

?

在客戶端顯示本地html的內容

java調用html文件,?webview?=?new?WebView(this);

?WebSettings?webseting?=?webview.getSettings();?
???webseting.setDefaultTextEncodingName("utf-8");//這個要和寫入本地hml的編碼一致

?webview.loadUrl("file:///"+htmlpath);?//顯示圖文

?