Android中阻止AlertDialog关闭实例代码
程序员文章站
2024-02-27 23:59:09
android如何关闭alertdialog.builder对话框呢?alertdialog.builder对话框没有类似finish()或者dismiss()这样的方法。...
android如何关闭alertdialog.builder对话框呢?alertdialog.builder对话框没有类似finish()或者dismiss()这样的方法。
但是它的父类alertdialog有dismiss方法,而且alertdialog.builder在.show()的时候会得到一个alertdialog对象,我们就可以用dismiss方法将该builder关闭。
alertdialog.builder builder = new alertdialog.builder(this); alertdialog dialog = builder.show(); dialog.dismiss();
关于android阻止alertdialog关闭具体代码如下所示:
alertdialog.builder builder = new alertdialog.builder(getactivity()); builder.settitle("测试"); layoutinflater inflater = getactivity().getlayoutinflater(); view view = inflater.inflate(r.layout.dialogfragment_num_input, null); builder.setview(view); builder.setpositivebutton("确定", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int id) { field field = null; try { //通过反射获取dialog中的私有属性mshowing field = dialog.getclass().getsuperclass().getdeclaredfield("mshowing"); field.setaccessible(true);//设置该属性可以访问 } catch (exception ex) { } string inputvalue = string.valueof(medit.gettext()); if (inputvalue == null || "".equals(inputvalue)) { try { //设置dialog不可关闭 field.set(dialog, false); dialog.dismiss(); } catch (exception ex) { } } else { // //做自己的事 // try { //关闭 field.set(dialog, true); dialog.dismiss(); } catch (exception ex) { } } } }); builder.setnegativebutton("取消", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int id) { field field = null; try { //通过反射获取dialog中的私有属性mshowing field = dialog.getclass().getsuperclass().getdeclaredfield("mshowing"); field.setaccessible(true);//设置该属性可以访问 } catch (exception ex) { } try { field.set(dialog, true); dialog.dismiss(); } catch (exception ex) { } } }); builder.create();