首先需要添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity:
package com.wyl.webview;import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener {WebView webview;ProgressDialog dialog;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}public void init() {webview = (WebView) findViewById(R.id.webview01);webview.loadUrl("http://www.baidu.com");webview.setWebViewClient(new WebViewClient() {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(url);return true;// 用webview打开,}});WebSettings settings = webview.getSettings();settings.setJavaScriptEnabled(true);// 允许jssettings.setCacheMode(settings.LOAD_CACHE_ELSE_NETWORK);// 使用缓存webview.setWebChromeClient(new WebChromeClient() {@Override// 这个方法可以检测网页的变化public void onProgressChanged(WebView view, int newProgress) {// newProgress 1-100之间的整数if (newProgress == 100) {// 网页加载完毕后,关闭进度条progressDialogcloseDialog(newProgress);} else {// 网页正在加载,打开dialogopenDialog(newProgress);}super.onProgressChanged(view, newProgress);}private void closeDialog(int newProgress) {if (dialog != null && dialog.isShowing()) {dialog.dismiss();// 取消显示dialog = null;}}private void openDialog(int newProgress) {//if (dialog == null) {dialog = new ProgressDialog(MainActivity.this);dialog.setTitle("我正在努力正在加载。。。");dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialog.setProgress(newProgress);// 显示当前的进度dialog.show();// 展示进度} else {// 如果已经有了dialog,只需要刷新进度就可以dialog.setProgress(newProgress);}}});}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {String url = webview.getUrl();Toast.makeText(MainActivity.this, "返回上一页,wyl," + url,Toast.LENGTH_SHORT).show();System.out.println("===toast===");if (webview.canGoBack()) {webview.goBack();return true;} else {System.exit(0);// 退出程序}}return super.onKeyDown(keyCode, event);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stub}}