http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/ 我对其进行了修改,并加了简单的注释,这个例子的不仅是对js的操作,它还对android浏览器做了简单的介绍,
这些我会在注释中一一讲解。
Javascript弹出框有如下三种:
- alert();
- window.confirm("Are you srue?");
- window.prompt("Please input some word";,"this is text");
WebChromeClient 中对三种dialog进行了捕捉,但不幸的是,并没有回调函数可以使用,
或者说不能获得用户是点击“OK”还是“CANCEL”的操作结果。
个人以为,这些方法的设置是为了对一些涉及到html操作的应用程序进行测试时使用的。
在WebChromeClient中还有以下的方法:
- onProgressChanged(WebView view, int newProgress);
- onReceivedIcon(WebView view, Bitmap icon);
- onReceivedTitle(WebView view, String title);
- onRequestFocus(WebView view);
- onCloseWindow(WebView window);
- onProgressChanged(WebView view, int newProgress)
这些方法的使用我会在以后的博文中讲到.
请大家先看今天讲解的重点
- public class WebViewDemo extends Activity {
-
- private static final String LOG_TAG = "WebViewDemo";
- private WebView mWebView;
- private TextView mReusultText ;
- private Handler mHandler = new Handler();
-
- @Override
- public void onCreate(Bundle icicle) {
-
- super.onCreate(icicle);
- setContentView(R.layout.main);
-
-
-
-
- mWebView = (WebView) findViewById(R.id.webview);
- mReusultText = (TextView) findViewById(R.id.resultText);
-
- WebSettings webSettings = mWebView.getSettings();
- webSettings.setSavePassword(false);
- webSettings.setSaveFormData(false);
- webSettings.setJavaScriptEnabled(true);
- webSettings.setSupportZoom(false);
- mWebView.setWebChromeClient(new MyWebChromeClient());
-
-
-
-
-
-
- mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"androd");
- mWebView.loadUrl("file:///android_asset/page.html");
- }
-
- final class DemoJavaScriptInterface {
- DemoJavaScriptInterface() {}
-
-
-
-
- public void clickOnAndroid() {
- mHandler.post(new Runnable() {
- public void run() {
-
- mWebView.loadUrl("javascript:onJsAndroid()");
- }
- });
- }
- }
-
-
-
-
-
-
- final class MyWebChromeClient extends WebChromeClient {
-
-
-
-
- @Override
- public boolean onJsAlert(WebView view,String url,
- String message,JsResult result) {
- Log.d(LOG_TAG,"onJsAlert:"+message");
- mReusultText.setText("Alert:"+message);
-
- new AlertDialog.Builder(WebViewDemo.this).
- setTitle("Alert").setMessage(message).setPositiveButton("OK",
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface arg0, int arg1) {
-
- }
- }).create().show();
- result.confirm();
- return true;
- }
-
-
-
-
- @Override
- public boolean onJsConfirm(WebView view, String url, String message,
- JsResult result) {
- Log.d(LOG_TAG, "onJsConfirm:"+message);
- mReusultText.setText("Confirm:"+message);
- result.confirm();
- return super.onJsConfirm(view, url, message, result);
- }
-
-
-
-
- @Override
- public boolean onJsPrompt(WebView view, String url, String message,
- String defaultValue, JsPromptResult result) {
- Log.d(LOG_TAG,"onJsPrompt:"+message);
- mReusultText.setText("Prompt input is :"+message);
- result.confirm();
- return super.onJsPrompt(view, url, message, message, result);
- }
- }
- }