In my app I have an AppCompatActivity which has a support fragment. From this fragment I am showing a DialogFragment as follows
final MyDialogFragment completeDialogFragment = MyDialogFragment.newInstance(titleString,
messageString, DialogType.Ok);
completeDialogFragment.setDialogCallBack(new MyDialogFragment.DialogCallBacks() {
@Override
public void onPositive() {
// some code to execute when Ok is pressed
completeDialogFragment.dismiss();
}
@Override
public void onNegative() {
// not relevant
}
});
completeDialogFragment.setCancelable(false);
FragmentManager mgr = getChildFragmentManager();
completeDialogFragment.show(mgr, MY_TAG);
As you can see I am attaching a listener interface to listen to positive / negative button clicks from the dialog fragment. This listener works as expected but when the device gets rotated, it is not. So I wanted to retain or reset this listener whenever the device is rotated. As many people suggested on stackoverflow, I tried to do it the following way in my fragment
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
FragmentManager mgr = getChildFragmentManager();
final MyDialogFragment completeDialogFragment =
(MyDialogFragment) mgr.findFragmentByTag(MY_TAG);
if (completeDialogFragment != null) {
completeDialogFragment
.setDialogCallBack(new MyDialogFragment.DialogCallBacks() {
@Override
public void onPositive() {
// some code to execute when Ok is pressed
completeDialogFragment.dismiss();
}
@Override
public void onNegative() {
// not relevant
}
});
}
}
}
In the above code segment I am trying to find the dialog fragment by its tag and reset the listener but the variable completeDialogFragment
is always null. I tried using getFragmentManager()
and getActivity().getSupportFragmentManager()
instead and it identifies the fragment but the dialog disappears from screen after rotation. Why the ChildFragmentManager is unable to identify the DialogFragment? Have anyone faced similar issue? Any help would be greatly appreciated.
If anyone is interested, the way I solved it was to use ChildFragmentManager
and use it in onCreateView()
instead of onCreate()
. Strange...