Reputation: 1707
I have an alertDialog in the onCreate() of my activity, which sets certain properties of the activity.
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("My Dialog");
alertDialogBuilder
.setCancelable(false)
...
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
When I start the activity, the dialog is started and after submitting the dialog the properties are set and the dialog is dismissed. So far so good.
However, if at this point (after submitting/dismissing the dialog), I rotate the device/screen, onCreate() is called again and the dialog is opened again (which I don't want).
How do I prevent opening the dialog on screen rotation? Or should I create the dialog somewhere else (not in onCreate() of the activity)?
Upvotes: 0
Views: 2055
Reputation: 1707
Based on Basil Battikhi's solution I ended up doing the following:
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// save whether dialog has been submitted
savedInstanceState.putBoolean("isSubmitted", isSubmitted);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onPause() {
super.onPause();
if ( alertDialog != null ) {
alertDialog.dismiss(); // prevent window leak when screen is rotated while dialog shown
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// check whether activity is recreated or created for the first time
if( savedInstanceState != null ) {
// recover information on whether dialog was submitted
isSubmitted = savedInstanceState.getBoolean("isSubmitted");
}
alertDialogBuilder.setPositiveButton("Start", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
...
isSubmitted=true;
})}
if ( !isSubmitted ) {
alertDialog.show();
}
Upvotes: 0
Reputation: 2668
your problem is onCreateMethod
called in each time you rotate the screen you can override onSaveInstanceState
method to save instance of your current layout
boolean isSubmited=false;
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putBoolean(isSubmited, true);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Now when you submit the dialog, change isSubmited
to true then type
if(isSubmited)
alertDialog.show();
reference http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Upvotes: 3