信息:我在 a 中有一个 2 窗格布局(2 个 child Fragments
)ParentFragment
,当然,它在 aFragmentActivity
中。我setRetainInstance(true)
在ParentFragment
. 在方向改变时,左子片段不会被破坏(onCreate()
不会被调用),这是正常的(因为父片段保留了它的实例)。
问题:在方向改变时,正确的片段被破坏(onCreate()
被调用)。为什么右边的碎片被破坏了而左边的碎片没有?
编辑:如果我删除setRetainInstance(true)
,则左侧片段onCreate()
被调用两次(lol wtf),右侧片段onCreate()
被调用一次。所以这也不好...
ParentFragment的代码如下:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
setHasOptionsMenu(true);
if (getChildFragmentManager().findFragmentById(R.id.fragment_schedule_framelayout_left) == null ||
!getChildFragmentManager().findFragmentById(R.id.fragment_schedule_framelayout_left).isInLayout())
{
if (mPresentationsListFragment == null)
mPresentationsListFragment = PresentationsListFragment.newInstance(PresentationsListFragment.TYPE_SCHEDULE, mScheduleDate);
getChildFragmentManager().beginTransaction()
.replace(R.id.fragment_schedule_framelayout_left, mPresentationsListFragment)
.commit();
}
mPresentationsListFragment.setOnPresentationClickListener(this);
return view;
}
@Override
public void onPresentationClick(int id)
{
if (Application.isDeviceTablet(getActivity()))
{
if (getChildFragmentManager().findFragmentById(R.id.fragment_schedule_framelayout_right) == null)
{
if (mPresentationDetailFragment == null)
mPresentationDetailFragment = PresentationDetailFragment.newInstance(id);
else
mPresentationDetailFragment.loadPresentation(id);
getChildFragmentManager().beginTransaction()
.replace(R.id.fragment_schedule_framelayout_right, mPresentationDetailFragment)
.commit();
}
else
mPresentationDetailFragment.loadPresentation(id);
}
else
{
Intent presentationDetailIntent = new Intent(getActivity(), PresentationDetailActivity.class);
presentationDetailIntent.putExtra(PresentationDetailActivity.KEY_PRESENTATION_ID, id);
startActivity(presentationDetailIntent);
}
}
LE解决方案:
非常感谢antonyt,答案如下。pe 执行的唯一更改位于 parent 的 onCreateView() 中Fragment
。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
setHasOptionsMenu(true);
if (getChildFragmentManager().findFragmentById(R.id.fragment_presentations_framelayout_left) == null)
{
mPresentationsListFragment = PresentationsListFragment.newInstance();
mPresentationsListFragment.setOnPresentationClickListener(this);
getChildFragmentManager().beginTransaction()
.add(R.id.fragment_presentations_framelayout_left, mPresentationsListFragment)
.commit();
}
return view;
}