---恢复内容开始---html
一.实例化WebViewjava
<WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
WebView webView = new WebView(this);android
二.加载网页git
一、LoadUrl 直接加载网页、图片并显示.(本地或是网络上的网页、图片、gif)(默认在浏览器中打开)github
使用LoadUrl 出现过的问题web
设置html的编码浏览器
<head> <title>这是标题</title> <meta name="content-type" content="text/html; charset=utf-8"> <meta http-equlv="Content-Type" content="text/html;charset=utf-8"> </ head>
webview.getSettings().setDefaultTextEncodingName("utf-8");
二、LoadData 显示文字与图片内容(模拟器1.五、1.6)网络
String htmlString = "<h1>Title</h1><p>This is HTML text<br /><i>Formatted in italics</i><br />Anothor Line</p>";
myWebView.loadData(htmlString, "text/html", "utf-8");
使用LoadData可能出现的问题ide
%,会报找不到页面错误,页面全是乱码。this
#,会让你的goBack失效,但canGoBAck是可使用的。因而就会产生返回按钮生效,但不能返回的状况。
\ 和? 在转换时,会报错,由于它会把\看成转义符来使用。
三、LoadDataWithBase 显示文字与图片内容(支持多个模拟器版本)没有试过,第一个参数和最后一个参数能够为null。推测:但这样就没有历史记录了。
void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)
三.如何加载网页:使用浏览器仍是Activity的webview
//全部都在webView中打开网页,不会使用浏览器打开网页了
myWebView.setWebViewClient(new WebViewClient()); myWebView.loadUrl("http://www.baidu.com");
private class MyWebViewClient extends WebViewClient { private final String TAG = MyWebViewClient.class.getSimpleName(); @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.e(TAG, url+" getHost:"+Uri.parse(url).getHost()); if (Uri.parse(url).getHost().equals("m.baidu.com")) { // This is my web site, so do not override; let my WebView load // the page。在webview中加载网页 return false; } // Otherwise, the link is not for a page on my site, so launch // another Activity that handles URLs.使用浏览器加载网页 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } //控制打开网页的地方 myWebView.setWebViewClient(new MyWebViewClient()); myWebView.loadUrl("http://www.baidu.com");
四.按返回键的时候按浏览历史退回,(前进使用myWebView.goForward();)
/** * 按键响应,在WebView中查看网页时,按返回键的时候按浏览历史退回,若是不作此项处理则整个WebView返回退出 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Check if the key event was the Back button and if there's history if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { /* * canGoBack() 方法在网页能够后退时返回true。 * 相似的,canGoForward()方法能够检查是否有能够前进的历史记录。 */ // 这个是前进 // myWebView.goForward(); // 返回键退回 myWebView.goBack(); return true; } // If it wasn't the Back key or there's no web page history, bubble up // to the default // system behavior (probably exit the activity) return super.onKeyDown(keyCode, event); }
代码示例:https://github.com/bigthing33/StudyDemo.git
在项目的WebViewActivity中.
---恢复内容结束---