I have an Activity that host a Fragment. In that Fragment I open a DialogFragment.
In the Fragment I call this function to show the dialog. Note that before showing the dialog I set an Interface defined in the DialogFragment.
private void showRatingDialog(){
if (getActivity() != null) return;
MyRatingDialog ratingDialog = new MyRatingDialog();
ratingDialog.setOnRatingDialog(new MyRatingDialog.OnRatingDialog() {
// some code
});
ratingDialog.show(getActivity().getSupportFragmentManager(), MyRatingDialog.TAG);
}
My MyRatingDialog class:
public class MyRatingDialog extends DialogFragment{
private OnRatingDialog onRatingDialog;
public interface OnRatingDialog{
void onSubmitRating(int rateSelected);
void onCancelRating();
}
public void setOnRatingDialog(OnRatingDialog onRatingDialog) {
this.onRatingDialog = onRatingDialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View layout = getActivity().getLayoutInflater().inflate(R.layout.dialog_rating, null, false);
alertDialog = new AlertDialog.Builder(getActivity()).setView(layout).create();
alertDialog.setCancelable(false);
ratingStarComponent = (RatingStarComponent)layout.findViewById(R.id.rating_star_component);
ratingStarComponent.setOnRateListener(new RatingStarComponent.OnRateListener() {
@Override
public void onRateClickListener(int starRate) {
rate = starRate;
}
});
Button rateButton = (Button)layout.findViewById(R.id.rate);
rateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onRatingDialog!=null) { // this is null after a configuration change
onRatingDialog.onSubmitRating(rate, optionsSelected, commentsEditText.getText().toString());
alertDialog.dismiss();
}
}
});
ImageView closeButton = (ImageView)layout.findViewById(R.id.close);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
return alertDialog;
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
onRatingDialog.onCancelRating();
}
}
The problem is that after a configurationChange like screen rotation or any other configurationChange, the interface onRatingDialog is null. My question is what is the best way/best practice to save the reference to onRatingDialog interface after a configurationChange? I wouldn't like to make the hosted Activity implements the interface, as I think it's more complex access to the dialog. By doing setRetainInstance(true) the dialog is closed after the configurationChange, so how can I mantain the dialog visible keeping the reference to the interface.
Thanks.