关闭

webview 理解

101人阅读 评论(0) 收藏 举报

Android.webkit.WebView本身就是一个浏览器实现,它的内核基于开源WebKit引擎。

常用方法:
void goBack():后退
void goForward():前进
void loadUrl(String url):加载网页
boolean ZoomIn():放大网页
boolean zoomOut():缩小网页

更多的请查阅官方文档(docs/reference/android/webkit/WebView.html)

1.加载URL对应的页面

<code class="hljs r has-numbering">WebView webview = (WebView) findViewById(R.id.webview);
<span class="hljs-keyword">...</span>
webview.loadUrl(<span class="hljs-string">"www.csdn.net"</span>);</code><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li></ul><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li></ul>

2.加载HTML代码

WebView提供了loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)方法,参数说明如下:

baseUrl:作为网页输入的网址(一般null)
data:需要加载的HTML代码
mimeType:指定HTML代码的MIME类型,HTML可指定为text/html
encoding:指定HTML代码的字符编码
historyUrl:历史输入的网址(一般null)
<code class="hljs avrasm has-numbering">WebView webview = (WebView) findViewById(R<span class="hljs-preprocessor">.id</span><span class="hljs-preprocessor">.webview</span>)<span class="hljs-comment">;</span>
StringBuilder sb = new StringBuilder()<span class="hljs-comment">;</span>
// 拼接一段HTML代码
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"<html>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"<head>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"<title> Test </title>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"</head>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"<body>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"<h2> Test Page </h2>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"</body>"</span>)<span class="hljs-comment">;</span>
sb<span class="hljs-preprocessor">.append</span>(<span class="hljs-string">"</html>"</span>)<span class="hljs-comment">;</span>
// 使用简单的loadData方法会导致乱码
// webview<span class="hljs-preprocessor">.loadData</span>(sb<span class="hljs-preprocessor">.toString</span>(), <span class="hljs-string">"text/html"</span>, <span class="hljs-string">"utf-8"</span>)<span class="hljs-comment">;</span>
// 加载、并显示HTML代码
webview<span class="hljs-preprocessor">.loadDataWithBaseURL</span>(null, sb<span class="hljs-preprocessor">.toString</span>(), <span class="hljs-string">"text/html"</span>, <span class="hljs-string">"utf-8"</span>, null)<span class="hljs-comment">;</span></code>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2101次
    • 积分:76
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:12篇
    • 译文:0篇
    • 评论:0条
    文章存档