Android与Javascript交互示例(三)
MainAcivity如下:
[java]
package cn.testjavascriptdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInte易做图ce;
import android.content.DialogInte易做图ce.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
/**
* Demo描述:
* 测试Android响应Javascript的三种对话框
*
* 参考资料:
* http://www.cnblogs.com/luckjun/archive/2013/03/22/2976117.html
*/
public class MainActivity extends Activity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
mWebView=(WebView) findViewById(R.id.webView);
initWebViewSettings();
// 为WebView设置WebChromeClient
mWebView.setWebChromeClient(new WebChromeClientSubClass());
//加载本地Html文件
mWebView.loadUrl("file:///android_asset/test.html");
}
private void initWebViewSettings(){
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.requestFocus();
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
}
private class WebChromeClientSubClass extends WebChromeClient{
@Override
public boolean onJsAlert(WebView view, String url, String message,final JsResult result) {
Dialog alertDialog=null;
AlertDialog.Builder builder=new Builder(MainActivity.this);
builder.setTitle("Javascript的alert对话框");
builder.setMessage(message);
builder.setNegativeButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInte易做图ce arg0, int arg1) {
System.out.println("现在显示的是Javascript的alert对话框");
//注意:
//必须要这一句代码:result.confirm()表示:
//处理结果为确定状态同时唤醒WebCore线程
//否则不能继续点击按钮
result.confirm();
}
});
alertDialog=builder.create();
alertDialog.show();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message,final JsResult result) {
Dialog confirmDialog=null;
AlertDialog.Builder builder=new Builder(MainActivity.this);
builder.setTitle("Javascript的confirm对话框");
builder.setMessage(message);
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInte易做图ce arg0, int arg1) {
System.out.println("现在点击的是Javascript的confirm对话框的OK");
//处理结果为确定状态同时唤醒WebCore线程
result.confirm();
}
});
&nb
补充:移动开发 , Android ,