弹出AlertDialog之后,点击空白处,默认Dialog消失;
点击回退键,默认消失;
那么如何点击空白处,不隐藏对话框,点击Android的返回键,跳回到上一个Activity?
直接看代码:
//*******************public static void showAlertDialog(final Context context, String title, CharSequence[] items, OnClickListener listener, boolean canceledOutside){ Builder builder = new AlertDialog.Builder(context).setTitle(title).setItems(items, listener); if(canceledOutside){ builder.show(); }else{ AlertDialog dialog = builder.create(); //点击dialog之外的空白处,dialog不能消失 dialog.setCanceledOnTouchOutside(false); dialog.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { //按back键,返回上一个Activity dialog.cancel(); boolean isActivity = context instanceof Activity; if(isActivity){ Activity act = (Activity)context; act.finish(); } return false; } return false; } }); dialog.show(); } }
dialog的dismiss 和cancel方法区别:
cancel会调用CancelListener,这是最大的区别,另外cancel会调用dismiss。