7C00.ME/houmu 2012-04-10

WebView学习相关笔记

打算做个简单的浏览器,先从WebView开始学期。从某社区网站上搜索,抄下了一些笔记。用代码的方式记了下来,如下。

// WebView 学习笔记

// 基本示例
// 来自 
// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=11763
class WebViewNote extends Activity{

private WebView webView;
private Handler handler = new Handler();

public void onCreate(Bundle bundle){
	//...
	//webView = (WebView) findViewById(...)

	// 载入页面
	webView.loadUrl("file:///android_asset/demo.html");
	// 从asset目录加载页面的语法结构如上

	// 载入页面的另一种方法
	// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=11241
	// webView.postUrl(url,postData);

	// 启用Javascript功能
	webView.getSettings().setJavaScriptEnabled(true);

	// 当前webView打开链接
	webView.setWebViewClient(new WebViewClient(){
		public boolean shouldOverrideUrlLoading(WebView view,String url){
			view.loadUrl(url);
			return true;
		}

		// WebViewClient中其他可重载的方法
		// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=1543

		public void onPageFinished(WebView view,String url){
			super.onPageFinished(view,url);
		}

		public void onPageStarted(WebView view,String url,Bitmap favicon){
			super.onPageStarted(view,url,favicon);
		}

		// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=1569
		public void onReceiveError(WebView view,int errorCode,
			String description,String failingUrl){
			// ...
		}

	});

	// 有关进度的设置,标题栏显示进度
	// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=1569
	getWindow().requestFeture(Window.FEATURE_RROGRESS);
	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 * 100);
		}
	});

	// 按Back键,后退而不退出程序
	// 见onKeyDown

	// 可以后退
	// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=1475
	// webView.canGoBack();

	// 与Js交互
	webView.addJavascriptInterface(new Object(){
		public void clickOnAndroid(){
			handler.post(new Runnable(){
				public void run(){
					webView.loadUrl("javasript:wave()");
				}
			},"demo");
		}
	});
	// 对应Html代码
	/*
	<html><script>function wave()
	{document.getElementById("droid").src="wave.png";}</script>
	<a onClick="window.demo.clickOnAndroid()">
	<img id="droid" src="normal.png"/></a></html>
	*/

}

public boolean onKeyDown(int keyCode, KeyEvent event) { 
	if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) { 
		webView.goBack(); 
		return true; 
	} 
	return super.onKeyDown(keyCode, event); 
}

// 另一个非常有参考意义的网址
// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=14219

// 对WebChromeClient有较多的举例,非常好!
//http://www.d-android.com/developer/forum.php?mod=viewthread&tid=15047

// webView 和 js 交互的简单而清晰的说明
// http://www.d-android.com/developer/forum.php?mod=viewthread&tid=23687

}