Android WebView Demo

来源:互联网 发布:淘宝开店的具体步骤 编辑:程序博客网 时间:2024/06/07 10:25

本文,主要入门式的介绍了WebView的使用方式,主要用到了两个比较重要的类:WebViewClient和WebChromeClient,并说明了两者之间的区别。在实际开发中,一般两者结合起来使用。

看代码:


activity_main布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:text="@string/hello_world" />    <WebView        android:id="@+id/webView"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></RelativeLayout>

MainActivity:

package com.webviewdemo;import android.app.Activity;import android.os.Bundle;import android.view.KeyEvent;import android.webkit.WebChromeClient;import android.webkit.WebView;import android.webkit.WebViewClient;public class MainActivity extends Activity {private WebView webView;private String Stringstr;final MainActivity activity = this;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webView = (WebView) findViewById(R.id.webView);webView.loadUrl("http://www.sohu.com");webView.setWebViewClient(new MyWebViewClient());webView.setWebChromeClient(new MyWebChromeClient());}/** * WebChromeClient相对WebChromeClient来说,这里主要是提供了 正在加载.. .提示功能。 *  * 那么两者有什么区别呢:  * WebViewClient主要帮助WebView处理各种通知、请求事件的,比如: *  * onLoadResource *  * onPageStart *  * onPageFinish *  * onReceiveError *  * onReceivedHttpAuthRequest *  * WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等,比如: *  * onCloseWindow(关闭WebView) *  * onCreateWindow() *  * onJsAlert (WebView上alert无效,需要定制WebChromeClient处理弹出) *  * onJsPrompt *  * onJsConfirm *  * onProgressChanged *  * onReceivedIcon *  * onReceivedTitle *  * 看上去他们有很多不同,实际使用的话,如果你的WebView只是用来处理一些html的页面内容,只用WebViewClient就行了, * 如果需要更丰富的处理效果,比如JS、进度条等,就要用到WebChromeClient。 */public class MyWebChromeClient extends WebChromeClient {@Overridepublic void onProgressChanged(WebView view, int newProgress) {super.onProgressChanged(view, newProgress);activity.setTitle("加载中...");activity.setProgress(newProgress * 100);if (newProgress == 100)activity.setTitle(R.string.app_name);}}/** * web视图客户端(不会再调用手机上安装的其他浏览器)! */public class MyWebViewClient extends WebViewClient {public boolean shouldOverviewUrlLoading(WebView view, String url) {view.loadUrl(url);return true;}}/** * 设置回退键。 如果不是调用手机系统或已安装的浏览器,则需要复写该方法。 这样,点击返回键后,网页会一步步返回。 否则,点击返回键后,直接退出应用。 */public boolean onKeyDown(int keyCode, KeyEvent event) {if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {webView.goBack();return true;}return super.onKeyDown(keyCode, event);}}

本文地址:

http://blog.csdn.net/u012440207/article/details/23194867

源码下载:

http://download.csdn.net/detail/u012440207/7162105

0 0
原创粉丝点击