码迷,mamicode.com
首页 > Web开发 > 详细

WebView之2

时间:2015-08-06 22:13:16      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

  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;

	@Override
	protected 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() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;// 用webview打开,
			}
		});

		WebSettings settings = webview.getSettings();
		settings.setJavaScriptEnabled(true);// 允许js
		settings.setCacheMode(settings.LOAD_CACHE_ELSE_NETWORK);// 使用缓存
		webview.setWebChromeClient(new WebChromeClient() {
			@Override
			// 这个方法可以检测网页的变化
			public void onProgressChanged(WebView view, int newProgress) {
				// newProgress 1-100之间的整数
				if (newProgress == 100) {
					// 网页加载完毕后,关闭进度条progressDialog
					closeDialog(newProgress);
				} else {
					// 网页正在加载,打开dialog
					openDialog(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);
				}
			}

		});

	}

	@Override
	public 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);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}

  

 

WebView之2

标签:

原文地址:http://www.cnblogs.com/Sunnor/p/4709158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!