builder.setPositiveButton("确定",(dialog,which)->{ String statisticExcelNamEditText = editText.getText().toString().trim(); if(TextUtils.isEmpty(statisticExcelNamEditText)){ ToastUtils.show("请输入Excel文件名!"); }else{ String statisticFilePath = Constant.EXCEL_FOLDER_PATH +statisticExcelNamEditText +".xls"; outputExcel(statisticInfo,statisticFilePath); dialog.dismiss(); } }); builder.setNegativeButton("取消",(dialog,which)->{ dialog.dismiss(); }); AlertDialog alertDialog = builder.create(); setAlertDialogManualDissMiss(alertDialog);// 阻止点击button时dissmis,需手动dissMiss alertDialog.show(); } /** * 设置AlertDialog 手动dismiss * 通过重新设置一个button处理类,达到点击确定按钮不dismiss掉dialog的效果 * @param dialog alertDialog */ private void setAlertDialogManualDissMiss(DialogInterface dialog) { try { Field field=null; //通过反射获取dialog中的私有属性mShowing if(! (dialog instanceof AlertDialog)){ return; } field= ((AlertDialog)dialog).getClass().getDeclaredField("mAlert"); //Field field = dialog.getClass().getDeclaredField("mAlert"); field.setAccessible(true); /* 获得mAlert变量的值 */ Object obj = field.get(dialog); field = obj.getClass().getDeclaredField("mHandler"); field.setAccessible(true); /* 修改mHandler变量的值,使用新的ButtonHandler类 */ field.set(obj, new Handler()); } catch (Exception e) { e.printStackTrace(); } } // 阻止dissmis 不起作用(可能是v7包的,本身包的没试) private void setAlertDialogCanDissmiss(DialogInterface dialog, boolean canDissmiss){ Field field = null; try { //通过反射获取dialog中的私有属性mShowing if(dialog instanceof AlertDialog){//v7包中的是父类 的父类 //要看清Dialog是他的父类还是父类的父类(即看清是哪个包的) field = ((AlertDialog)dialog).getClass().getSuperclass().getSuperclass().getDeclaredField("mShowing"); } field.setAccessible(true);//设置该属性可以访问 field.set(dialog, canDissmiss);//false can,true not can // dialog.dismiss(); } catch (Exception ex) { ex.printStackTrace(); System.out.println("--->ex" +ex.getMessage()); } }
Android 阻止AlertDialog dismiss
最新推荐文章于 2024-03-18 22:32:10 发布