Skip to content

Instantly share code, notes, and snippets.

@Audhil
Last active February 11, 2018 14:27
Show Gist options
  • Save Audhil/f53c9cc2c9477dd4bd2e05bf3df69b19 to your computer and use it in GitHub Desktop.
Save Audhil/f53c9cc2c9477dd4bd2e05bf3df69b19 to your computer and use it in GitHub Desktop.
AlertDialog - Trick to survive orientation change
// showing alert dialog
private void showAlertDialog(int pos, String optionTxt) {
final EditText edittext = new EditText(getApplicationContext());
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.optionSpace) + (pos + 1))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("ding! Ok clicked!");
}
})
.setView(edittext)
.setNegativeButton("Cancel", null)
.show();
      // this is VERY IMPORTANT -> ALWAYS APPLY THE TRICK ONLY AFTER .show() YOUR DIALOG
doKeepDialog(dialog);
}
// prevent from orientation change
private void doKeepDialog(AlertDialog dialog) {
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment