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();
【Android中阻止AlertDialog关闭实例代码】相关文章:
★ Android View添加 Listener 实例代码