Android如何关闭AlertDialog.Builder对话框呢?AlertDialog.Builder对话框没有类似finish()或者dismiss()这样的方法。
但是它的父类AlertDialog有dismiss方法,而且AlertDialog.Builder在.show()的时候会得到一个AlertDialog对象,我们就可以用dismiss方法将该Builder关闭。
1
2
3
|
AlertDialog.Builder builder = new AlertDialog.Builder( this ); AlertDialog dialog = builder.show(); dialog.dismiss(); |
关于Android阻止AlertDialog关闭具体代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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(); |