WebView
是View的一个子类,可让你在activity中显示网页。html
能够在布局文件中写入WebView:好比下面这个写了一个填满整个屏幕的WebView: java
<?xml version="1.0" encoding="utf-8"?><WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
加载一个网页,使用loadUrl()
:android
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.loadUrl(http://www.example.com);
注意要在manifest中加上访问网络的权限:web
<manifest ... > <uses-permission android:name="android.permission.INTERNET" /> ... </manifest>
设置WevView要显示的网页方法有不少:浏览器
互联网页面直接用: 网络
myWebView.loadUrl(“http://www.google.com“);
本地文件用:ide
myWebView.loadUrl(“file:///android_asset/XX.html“);
本地文件存放在:assets文件中。布局
还能够直接载入html的字符串,如:google
String htmlString = "<h1>Title</h1><p>This is HTML text<br /><i>Formatted in italics</i><br />Anothor Line</p>";// 载入这个html页面myWebView.loadData(htmlString, "text/html", "utf-8");
若是你想要载入的页面中用了JavaScript,你必须为你的WebView使能JavaScript。spa
一旦使能以后,你也能够本身建立接口在你的应用和JavaScript代码间进行交互。
使能JavaScript
能够经过getSettings()
得到WebSettings,而后用setJavaScriptEnabled()
使能JavaScript:
WebView myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true);
WebSettings中提供了不少有用的设置。
当用户点击了你的WebView中的一个连接,默认的行为是Android启动一个处理URL的应用,一般,默认的浏览器打开并下载目标URL。
可是,你能够在你的WebView中覆盖这一行为,使得链接仍在你的WebView中打开。
以后,根据在WebView中维护的网页浏览历史,你能够容许用户向前或向后浏览他们的网页。
在WebView中打开全部连接
要打开用户点击的连接,只须要用setWebViewClient()方法向你的WebView提供一个WebViewClient
好比:
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setWebViewClient(new WebViewClient());
此时就OK了, 就能够在你的WebView中打开连接了。
关于打开连接位置的更多控制
若是你对在哪里打开连接须要更多的控制,你能够建立本身的类,继承 WebViewClient
,而后覆写shouldOverrideUrlLoading()
方法。
好比下面这个:
MyWebViewClient Intent intent =
将特定的连接用本身的WebView打开,其余连接用浏览器(intent启动了默认的处理URL的Activity)。
定义完以后把这个类的对象传入setWebViewClient()方法便可。
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setWebViewClient(new MyWebViewClient());
实践验证:在直接设置setWebViewClient(new WebViewClient());时验证正确,即全部连接都是在WebView中打开。
在设置为自定义的WebViewClient子类对象时,发现连接仍然都是从默认浏览器中打开。
浏览网页历史回退
当你的WebView覆写了URL载入的行为,它会自动地对访问过的网页积累一个历史,你能够利用 goBack()
和 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()) { // 返回键退回 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); }
canGoBack() 方法在网页能够后退时返回true。
相似的,canGoForward()方法能够检查是否有能够前进的历史记录。
若是你不执行这种检查,一旦 goBack() 和 goForward()
方法到达历史记录顶端,它们将什么也不作。
若是不加这种设置,在用户按下Back键时,若是是WebView显示网页,则会将WebView做为总体返回。