Closed isabsent closed 4 years ago
Thanks @isabsent for this. I'll try to figure it out.
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());
}
This should be managed from the Activity
side I think. Whoever is creating dialog that should take care of that.
My code above is the way to take care about it.
Yes. I liked your suggestion. Will try to release next version with this.
You have to use
DialogFragment
as a base class for your dialogs to avoid this problem.