WebView学习记录

来源:互联网 发布:visio网络形状库下载 编辑:程序博客网 时间:2024/06/06 03:18

Android WebView文档学习记录

使用WebView组件进行网页访问,首先添加访问Internet权限:

Android Manifest中添加:

<uses-permission android:name="android.permission.INTERNET" />

在Activity中使用WebView需要在Layout中设置相关的<webview>配置,或者在onCreate()中:

WebView webview = new WebView(this); setContentView(webview);

下面就可以使用WebView进行网页访问了,简单的示例:

// Simplest usage: note that an exception will NOT be thrown // if there is an error loading this page (see below). webview.loadUrl("http://slashdot.org/"); // OR, you can also load from an HTML string: String summary = "<html><body>You scored <b>192</b> points.</body></html>"; webview.loadData(summary, "text/html", null); // ... although note that there are restrictions on what this HTML can do. // See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.

下面是WebView中一些可定制的组件:

1.WebChromeClient:用来自动处理可能会导致Ui出错的事物,比如JavaScript alerts。

2.WebViewClient::用来自动处理导致内容显示有影响的事物。经验表明设置该client后点击页面内的链接就能保持在该WebView内继续访问网页,而不会跳转到默认浏览器。

3.WebSettings:用来修饰该浏览器的一些设置,比如可以使该浏览器支持javaScript就可以调用setJavaScriptEnabled()。

4.addJavascriptInterface(Object, String):用来向浏览器注入java object,暂时不清楚具体做什么的。


一个稍微复杂一点的例子:

// Let's display the progress in the activity title bar, like the // browser app does. getWindow().requestFeature(Window.FEATURE_PROGRESS); webview.getSettings().setJavaScriptEnabled(true); final Activity activity = this; webview.setWebChromeClient(new WebChromeClient() {   public void onProgressChanged(WebView view, int progress) {     // Activities and WebViews measure progress with different scales.     // The progress meter will automatically disappear when we reach 100%     activity.setProgress(progress * 1000);   } }); webview.setWebViewClient(new WebViewClient() {   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();   } }); webview.loadUrl("http://developer.android.com/");

0 0
原创粉丝点击