我的 Android 应用程序中有以下结构:
[Main FragmentActivity] -> [DialogFragment #1] -> [DialogFragment #2] -> [DialogFragment #3 (Calendar / Datepicker)]
现在,当我在DialogFragment #3中选择日期并旋转设备并恢复之前的状态时,DialogFragment #3不再附加到DialogFragment #2而是附加到主要活动(Main片段活动)。
为什么会发生这种情况,我该如何防止这种行为?
编辑 1:
我正在使用支持库。
这里的每个请求是用于显示片段的代码。
显示DialogFragment #1
String tag = classDialog_1.class.getCanonicalName();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(tag);
if(prev != null)
fragmentTransaction.remove(prev);
fragmentTransaction.addToBackStack(null);
classDialog_1 instanceClassDialog_1 = classDialog_1.newInstance();
instanceClassDialog_1.show(fragmentTransaction, tag);
显示DialogFragment #2
String tag = classDialog_2.class.getCanonicalName();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag(tag);
if(prev != null)
fragmentTransaction.remove(prev);
fragmentTransaction.addToBackStack(null);
classDialog_1 instanceClassDialog_2 = classDialog_2.newInstance(paramA, paramB);
instanceClassDialog_2.show(fragmentTransaction, tag);
显示DialogFragment #3
String tag = this.getClass().getName() + classDialog_3.class.getCanonicalName();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag(tag);
if (prev != null)
fragmentTransaction.remove(prev);
fragmentTransaction.addToBackStack(null);
classDialog_3 instanceClassDialog_3 = classDialog_3.newInstance(paramC, paramD, paramE);
instanceClassDialog_3.show(fragmentTransaction, tag);
编辑 2:
正如下面的答案中所建议的,代码被修改如下但没有工作(例如DialogFragment #3):
String tag = this.getClass().getName() + classDialog_3.class.getCanonicalName();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag(tag);
/* This section wasn't removed since without it the dialog ( instanceClassDialog_3 ) wasn't showing up. */
if (prev != null)
fragmentTransaction.remove(prev);
fragmentTransaction.addToBackStack(null);
classDialog_3 instanceClassDialog_3 = classDialog_3.newInstance(paramC, paramD, paramE);
instanceClassDialog_3.show(fragmentTransaction, tag);