Android WebView封装及定制js的alert,confirm和prompt对话框的方法

1、对webview封装,在遇到加载页面时可以调用。

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >
 
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <WebView
            android:id="@+id/webView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

        <LinearLayout 
			android:id="@+id/ll_loading_dialog"
			android:layout_width="match_parent"
			android:layout_height="match_parent"
			android:gravity="center"
			android:background="#88000000"
			android:orientation="vertical"
			android:visibility="visible" >

			<ProgressBar
				android:layout_width="60dip"
				android:layout_height="60dip" />

			<TextView
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:text="@string/data_loading"
				android:textColor="@android:color/white"
				android:textSize="@dimen/font_body_12" />

		</LinearLayout>
    </FrameLayout>
 </LinearLayout>
2、java代码

public class Web {

	public Web(Activity activity) {
		super();
		this.activity = activity;
		initWebView();
	}

	private Activity activity;
	private LinearLayout mLoadingLayout;

	private WebView mWebView;

	/**
	 * 加载详情
	 */

	private void initWebView() {
		mWebView = (WebView) activity.findViewById(R.id.webView);
		mLoadingLayout = (LinearLayout) activity
				.findViewById(R.id.ll_loading_dialog);
		mWebView.setBackgroundColor(0);
		WebSettings webSettings = mWebView.getSettings();
		mWebView.requestFocus();
		webSettings.setJavaScriptEnabled(true);
		mWebView.setFocusable(true);
		webSettings.setBuiltInZoomControls(true);

		mWebView.setScrollBarStyle(0);

		mWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				Logger.getLogger().i("-----web------"+newProgress);
				if (newProgress>=100) {
					mWebView.loadUrl(method);
					Logger.getLogger().i("-----web load finish ------> "+newProgress);
				}
				super.onProgressChanged(view, newProgress);
			}
			
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());  
                
		        builder.setMessage(message).setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						 dialog.dismiss();
						 result.confirm();
					}
				});  
		        builder.setOnKeyListener(new OnKeyListener() {  
		            public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {  
		                return true;  
		            }  
		        });  
		        // 禁止响应按back键的事件  
		        builder.setCancelable(false);  
		        AlertDialog dialog = builder.create();  
		        dialog.show();  
		        return true;  
			}
			
		});

		mWebView.setWebViewClient(new WebViewClient() {
			// 重写父类方法,让新打开的网页在当前的WebView中显示
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				loadUrl(view, url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				mLoadingLayout.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				mLoadingLayout.setVisibility(View.VISIBLE);
				super.onPageStarted(view, url, favicon);
			}
		});

	}

	public void loadUrl(String url) {
		loadUrl(mWebView, url);
	}

	private void loadUrl(final WebView webView, final String url) {
		webView.loadUrl(url);
	}
	/**
	 * 加载方法,网页加载完毕时加载方法,防止加载不到方法
	 * @param method
	 */
	public void loadMethod(String method){
		Logger.getLogger().i(method);
		this.method = method;
	}
	
	private String method=null;
}

3、调用

	Web mWeb = new Web(this);
	mWeb.loadUrl("url");
	mWeb.loadMethod("javascript:show()");



4、定制对话框

1.首先继承android.webkit.WebChromeClient实现MyWebChromeClient。 

2.在MyWebChromeClient.java中覆盖onJsAlert,onJsConfirm,onJsPrompt三个方法。 

3.在初始化Webview时设置调用webview.setWebChromeClient(new MyWebChromeClient()); 

4.在Webview载入的html中使用window.alert,window.confirm,window.prompt方法,系统弹出的将是自定义实现的对应对话框。 

MyWebChromeClient.java的代码如下: 

Java代码   收藏代码
  1. import android.app.AlertDialog;  
  2. import android.content.DialogInterface;  
  3. import android.content.DialogInterface.OnCancelListener;  
  4. import android.content.DialogInterface.OnClickListener;  
  5. import android.content.DialogInterface.OnKeyListener;  
  6. import android.graphics.Bitmap;  
  7. import android.os.Message;  
  8. import android.util.Log;  
  9. import android.view.KeyEvent;  
  10. import android.webkit.JsPromptResult;  
  11. import android.webkit.JsResult;  
  12. import android.webkit.WebChromeClient;  
  13. import android.webkit.WebView;  
  14. import android.widget.EditText;  
  15.   
  16. /** 
  17.  * http://618119.com/archives/2010/12/20/199.html 
  18.  */  
  19.   
  20. //****************************************************************************  
  21. public class MyWebChromeClient extends WebChromeClient {  
  22.     @Override  
  23.     public void onCloseWindow(WebView window) {  
  24.         super.onCloseWindow(window);  
  25.     }  
  26.   
  27.     @Override  
  28.     public boolean onCreateWindow(WebView view, boolean dialog,  
  29.             boolean userGesture, Message resultMsg) {  
  30.         return super.onCreateWindow(view, dialog, userGesture, resultMsg);  
  31.     }  
  32.   
  33.     /**  
  34.      * 覆盖默认的window.alert展示界面,避免title里显示为“:来自file:  
  35.      */  
  36.     public boolean onJsAlert(WebView view, String url, String message,  
  37.             JsResult result) {  
  38.         final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());  
  39.                   
  40.         builder.setTitle("对话框")  
  41.                 .setMessage(message)  
  42.                 .setPositiveButton("确定"null);  
  43.                   
  44.         // 不需要绑定按键事件  
  45.         // 屏蔽keycode等于84之类的按键  
  46.         builder.setOnKeyListener(new OnKeyListener() {  
  47.             public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {  
  48.                 Log.v("onJsAlert""keyCode==" + keyCode + "event="+ event);  
  49.                 return true;  
  50.             }  
  51.         });  
  52.         // 禁止响应按back键的事件  
  53.         builder.setCancelable(false);  
  54.         AlertDialog dialog = builder.create();  
  55.         dialog.show();  
  56.         result.confirm();// 因为没有绑定事件,需要强行confirm,否则页面会变黑显示不了内容。  
  57.         return true;  
  58.         // return super.onJsAlert(view, url, message, result);  
  59.     }  
  60.   
  61.     public boolean onJsBeforeUnload(WebView view, String url,  
  62.             String message, JsResult result) {  
  63.         return super.onJsBeforeUnload(view, url, message, result);  
  64.     }  
  65.   
  66.     /** 
  67.      * 覆盖默认的window.confirm展示界面,避免title里显示为“:来自file:” 
  68.      */  
  69.     public boolean onJsConfirm(WebView view, String url, String message,  
  70.             final JsResult result) {  
  71.         final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());  
  72.         builder.setTitle("对话框")  
  73.                 .setMessage(message)  
  74.                 .setPositiveButton("确定",new OnClickListener() {  
  75.                             public void onClick(DialogInterface dialog,int which) {  
  76.                                 result.confirm();  
  77.                             }  
  78.                         })  
  79.                 .setNeutralButton("取消"new OnClickListener() {  
  80.                     public void onClick(DialogInterface dialog, int which) {  
  81.                         result.cancel();  
  82.                     }  
  83.                 });  
  84.         builder.setOnCancelListener(new OnCancelListener() {  
  85.             @Override  
  86.             public void onCancel(DialogInterface dialog) {  
  87.                 result.cancel();  
  88.             }  
  89.         });  
  90.   
  91.         // 屏蔽keycode等于84之类的按键,避免按键后导致对话框消息而页面无法再弹出对话框的问题  
  92.         builder.setOnKeyListener(new OnKeyListener() {  
  93.             @Override  
  94.             public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {  
  95.                 Log.v("onJsConfirm""keyCode==" + keyCode + "event="+ event);  
  96.                 return true;  
  97.             }  
  98.         });  
  99.         // 禁止响应按back键的事件  
  100.         // builder.setCancelable(false);  
  101.         AlertDialog dialog = builder.create();  
  102.         dialog.show();  
  103.         return true;  
  104.         // return super.onJsConfirm(view, url, message, result);  
  105.     }  
  106.   
  107.     /** 
  108.      * 覆盖默认的window.prompt展示界面,避免title里显示为“:来自file:” 
  109.      * window.prompt('请输入您的域名地址', '618119.com'); 
  110.      */  
  111.     public boolean onJsPrompt(WebView view, String url, String message,  
  112.             String defaultValue, final JsPromptResult result) {  
  113.         final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());  
  114.                   
  115.         builder.setTitle("对话框").setMessage(message);  
  116.                   
  117.         final EditText et = new EditText(view.getContext());  
  118.         et.setSingleLine();  
  119.         et.setText(defaultValue);  
  120.         builder.setView(et)  
  121.                 .setPositiveButton("确定"new OnClickListener() {  
  122.                     public void onClick(DialogInterface dialog, int which) {  
  123.                         result.confirm(et.getText().toString());  
  124.                     }  
  125.           
  126.                 })  
  127.                 .setNeutralButton("取消"new OnClickListener() {  
  128.                     public void onClick(DialogInterface dialog, int which) {  
  129.                         result.cancel();  
  130.                     }  
  131.                 });  
  132.   
  133.         // 屏蔽keycode等于84之类的按键,避免按键后导致对话框消息而页面无法再弹出对话框的问题  
  134.         builder.setOnKeyListener(new OnKeyListener() {  
  135.             public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {  
  136.                 Log.v("onJsPrompt""keyCode==" + keyCode + "event="+ event);  
  137.                 return true;  
  138.             }  
  139.         });  
  140.   
  141.         // 禁止响应按back键的事件  
  142.         // builder.setCancelable(false);  
  143.         AlertDialog dialog = builder.create();  
  144.         dialog.show();  
  145.         return true;  
  146.         // return super.onJsPrompt(view, url, message, defaultValue,  
  147.         // result);  
  148.     }  
  149.   
  150.     @Override  
  151.     public void onProgressChanged(WebView view, int newProgress) {  
  152.         super.onProgressChanged(view, newProgress);  
  153.     }  
  154.   
  155.     @Override  
  156.     public void onReceivedIcon(WebView view, Bitmap icon) {  
  157.         super.onReceivedIcon(view, icon);  
  158.     }  
  159.   
  160.     @Override  
  161.     public void onReceivedTitle(WebView view, String title) {  
  162.         super.onReceivedTitle(view, title);  
  163.     }  
  164.   
  165.     @Override  
  166.     public void onRequestFocus(WebView view) {  
  167.         super.onRequestFocus(view);  
  168.     }  
  169. }  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值