[Android_Webview]WebView的基本用法
1、WebView 显示进度条 在onCreate事件里写:
[java] view plaincopy
- WebView myWebView = (WebView) findViewById(R.id.webView1);
- final Activity activity = this;
- myWebView.setWebChromeClient(new WebChromeClient() {
- public void onProgressChanged(WebView view, int progress) {
- activity.setTitle("正在努力为您加载....");
- activity.setProgress(progress * 100);
- if(progress == 100)
- activity.setTitle("已完成");//或者设置为原有的Activity标题
- }
- });
2、网页自适应webView宽度 在onCreate事件里写:
[java] view plaincopy
- WebView myWebView = (WebView) findViewById(R.id.webView1);
- myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
3、webView支持网页JavaScript语言 在onCreate事件里写:
[java] view plaincopy
- WebView myWebView = (WebView) findViewById(R.id.webView1);
- myWebView.getSettings().setJavaScriptEnabled(true);
4、网页里面超链接在webview里加载而不是在手机默认浏览器打开 在onCreate事件里写:
[java] view plaincopy
- WebView myWebView = (WebView) findViewById(R.id.webView1);
[java] view plaincopy
- myWebView.setWebViewClient(new WebViewClient(){
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- view.loadUrl(url);
- return true;
- }
- });
[java] view plaincopy
- myWebView.loadUrl("http://www.baidu.com"));//默认加载url只能放在setWebViewClient后面 否则网页里面超链接还是在手机默认浏览器打开而不是在WebView里加载
5、按手机返回按钮后退网页而不是打开WebView程序之前的界面:
[java] view plaincopy
- public boolean onKeyDown(int keyCode, KeyEvent event)
- { // Check if the key event was the BACK key and if there's history
- WebView myWebView = (WebView) findViewById(R.id.webView1);
- if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
- {
- myWebView.goBack();
- return true;
- } // If it wasn't the BACK key or there's no web page history, bubble up to the default // system behavior (probably exit the activity)
- return super.onKeyDown(keyCode, event);
- }
6、网页Js调用Android程序:
新建一类JavaScriptInterface
[java] view plaincopy
- package com.example.androidhouse;
- import android.content.Context;
- import android.widget.Toast;
- public class JavaScriptInterface {
- Context mContext;
- /** Instantiate the interface and set the context */
- JavaScriptInterface(Context c) { mContext = c; }
- /** Show a toast from the web page */
- public void showToast(String toast)
- {
- Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
- }
- }
在onCreate事件里写:
[java] view plaincopy
- WebView myWebView = (WebView) findViewById(R.id.webView1);
[java] view plaincopy
- myWebView.addJavascriptInterface(new JavaScriptInterface(this),"Android");
网页js代码里写:
[javascript] view plaincopy
- window.Andorid.showToast("我调用的Android程序");
切记:在Andorid2.2 和Android2.3里面 webview的js调用会引起系统崩溃出现vm aborting错误 这是这两个版本的BUG 解决起来很麻烦 到现在为止,我仍未找到解决的办法。