WebView的根本使用
WebView的基本使用
---恢复内容开始---
一.实例化WebView
- 通过xml实例化
- xml
<WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
- myWebView = (WebView) findViewById(R.id.webview);
- xml
- 通过java代码动态实例化
WebView webView = new WebView(this);
二.加载网页
1、LoadUrl 直接加载网页、图片并显示.(本地或是网络上的网页、图片、gif)(默认在浏览器中打开)
- 互联网用:webView.loadUrl("http://www.google.com");
- 本地文件用:webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放在:assets 文件中
2、LoadData 显示文字与图片内容(模拟器1.5、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");
3、LoadDataWithBase 显示文字与图片内容(支持多个模拟器版本)没有试过
三.如何加载网页:使用浏览器还是Activity的webview
-
//所有都在webView中打开网页,不会使用浏览器打开网页了
myWebView.setWebViewClient(new WebViewClient()); myWebView.loadUrl("http://www.baidu.com");
- 重写WebViewClient类,控制网页打开是在浏览器打开还是Activity的WebView中打开
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中.
---恢复内容结束---