PatilShreyas / MaterialDialog-Android

📱Android Library to implement animated, 😍beautiful, 🎨stylish Material Dialog in android apps easily.
Apache License 2.0
939 stars 143 forks source link

Dialog dissappers after orientation changes. #24

Closed isabsent closed 4 years ago

isabsent commented 4 years ago

You have to use DialogFragment as a base class for your dialogs to avoid this problem.

PatilShreyas commented 4 years ago

Thanks @isabsent for this. I'll try to figure it out.

isabsent commented 4 years ago

This dialog will alive after screen rotation and will keep all inputs if you add custom layouts into it:

public class RotationSafeDialog extends DialogFragment {
    private String message;
    private Activity act;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            act = (MainActivity) context;
        } catch (ClassCastException castException) {

        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                act = (MainActivity) activity;
            } catch (ClassCastException castException) {

            }
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        act = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        message = getArguments().getString(EXTRA_ARGS_MESSAGE);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog dialog = new AlertDialog.Builder(act)
                .setTitle("Title")
                .setMessage(message)
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }
                )
                .create();
        return dialog;
    }
}

Call it with

public void showRotationSafeDialog(String message){
    Bundle args = new Bundle();
    args.putString("EXTRA_ARGS_MESSAGE", message);
    RotationSafeDialog dialog = new RotationSafeDialog();
    dialog.setArguments(args);
    dialog.show(getSupportFragmentManager(), dialog.getClass().getName());
}
PatilShreyas commented 4 years ago

This should be managed from the Activity side I think. Whoever is creating dialog that should take care of that.

isabsent commented 4 years ago

My code above is the way to take care about it.

PatilShreyas commented 4 years ago

Yes. I liked your suggestion. Will try to release next version with this.