Prevent AlertDialog from closing instance code in Android

  • 2021-06-28 09:44:22
  • OfStack

How does Android close the AlertDialog.Builder dialog?The AlertDialog.Builder dialog box has no methods like finish () or dismiss ().

However, its parent AlertDialog has the dismiss method, and AlertDialog.Builder gets an AlertDialog object at.show(), so we can turn it off using the dismiss method.


AlertDialog.Builder builder = new AlertDialog.Builder(this); 
AlertDialog dialog = builder.show(); 
dialog.dismiss(); 

The specific code for Android preventing AlertDialog from closing is as follows:


AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(" test ");
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialogfragment_num_input, null);
builder.setView(view);
builder.setPositiveButton(" Determine ",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Field field = null;
try {
// Get by Reflection dialog Private properties in mShowing
field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);// Set this property to be accessible 
} catch (Exception ex) {
}
String inputValue = String.valueOf(mEdit.getText());
if (inputValue == null || "".equals(inputValue)) {
try {
// Set up dialog Not Closable 
field.set(dialog, false);
dialog.dismiss();
} catch (Exception ex) {
}
} else {
//
// Do your own thing 
//
try {
// Close 
field.set(dialog, true);
dialog.dismiss();
} catch (Exception ex) {
}
}
}
});
builder.setNegativeButton(" cancel ",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Field field = null;
try {
// Get by Reflection dialog Private properties in mShowing
field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);// Set this property to be accessible 
} catch (Exception ex) {
}
try {
field.set(dialog, true);
dialog.dismiss();
} catch (Exception ex) {
}
}
});
builder.create();


Related articles: