Alert dialog closed while rotating the screen
In an android app I have an alert dialog ,while rotating the screen it gets dismissed ,I have find lot of solutions in stack overflow similar to this but not for my issue...
This is my Alert Dialog coding...
private void callchangepswd() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setCancelable(true);
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.changepassword, null, false);
EditText cemail = (EditText) view.findViewById(R.id.chagepswd_mail);
EditText cphone = (EditText) view.findViewById(R.id.chagepswd_phone);
Button verify=(Button)view.findViewById(R.id.verifybtn);
alertDialog.setView(view);
final AlertDialog dialogShow = alertDialog.create();
dialogShow.show();
verify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogShow.dismiss();
newpassword();
}
});
}
can anyone help to come out from this.....
When rotating the screen the Activity
is destroyed and recreated. That is why your Dialog
disappears.
In order to handle this situation you can override onSaveInstanceState
, keep a boolean
in the bundle telling you if the dialog was displayed. You should also keep the user input (phone and email).
And onRestoreInstanceState
you need to recreate the dialog and fill the fields with the user input. You can read more about the activity lifecycle here
您必须使用DialogFragment而不是AlertDialog,正如https://developer.android.com/guide/topics/ui/dialogs.html中所述。DialogFragment将在方向更改期间继续存在
No need to work with SaveInstanceState
. You can save your activity state (including your dialog) after a device rotation by adding orientation|screenSize
to your android:configChanges
property of activity
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
As it is correctly pointed out by @greenapps in the comment, you should add android:configChanges="orientation|screenSize"
to each activity where you call your dialog.
上一篇: 需要Prototype设计模式?
下一篇: 警报对话框在旋转屏幕时关闭