Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.4 kB
1
Indexable
Never
public class YourActivity extends AppCompatActivity {

    private AlertDialog alertDialog;
    private static final String DIALOG_KEY = "dialog_key";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState != null) {
            alertDialog = (AlertDialog) savedInstanceState.getSerializable(DIALOG_KEY);
            if (alertDialog != null && !alertDialog.isShowing()) {
                alertDialog.show();
            }
        } else {
            createAndShowDialog();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (alertDialog != null && alertDialog.isShowing()) {
            outState.putSerializable(DIALOG_KEY, alertDialog);
        }
    }

    private void createAndShowDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Your Title")
                .setMessage("Your Message")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Handle positive button click
                    }
                });

        alertDialog = builder.create();
        alertDialog.show();
    }
}
Leave a Comment