webview中back键拦截,弹出窗口进行确认
1.在android中拦截实现
webView.loadUrl("file:///android_asset/index.html"); //webview界面 webView.setOnKeyListener(new View.OnKeyListener() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //创建弹出窗口 @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { Log.e("onKey", keyEvent.toString()); if(KeyEvent.KEYCODE_BACK == i && 0 == keyEvent.getRepeatCount() && KeyEvent.ACTION_DOWN == keyEvent.getAction()) { if (webView != null && webView.canGoBack()) { webView.goBack(); } else { builder.setTitle("是否确定退出"); builder.setPositiveButton("确定退出", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //点击确定退出的处理方式 finish(); } }); builder.setNegativeButton("取消退出", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //点击取消键的处理方式 } }); builder.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) { //在弹出窗口下,再次点击返回键的处理方式。 if(KeyEvent.KEYCODE_BACK == i) return true; //使返回键无效 return false; } }); builder.create().show(); //弹出窗口 return true; //返回键拦截 } } return false; //其他键,照常响应。 } });