这两天用webview加载html时遇到很多问题也学到了不少,仅在这里记载以供以后参考,哪里不完善的还望有心人多加补充。

(这里只介绍webview.loadUrl())

思路:拿到网页url,然后把网页上的html写到本地文件中,然后用 webview.loadUrl("file:///"+htmlpath)加载图文。

 

注意:

1.写到本地文件时的编码要和加载本地文件时的编码一样,否则乱码!

2.html文件里的字体要使用同一种字体,否则客户端显示出来用其他字体的文字会出现乱码(这个可是我对照html文件好久才发现的哦)。

 

以下是代码块:

//定义本地路径
  htmlpath= FileUtils.getSDPATH()+"common_page_content/"+p_w_picpathName+".html";

 

 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)
 {

  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的内容

 webview = new WebView(this);

 WebSettings webseting = webview.getSettings(); 
   webseting.setDefaultTextEncodingName("utf-8");//这个要和写入本地hml的编码一致

 webview.loadUrl("file:///"+htmlpath); //显示图文