0
我有两个片段friendListFragment和logListFragment。来自后台的流行片段并再次添加它
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FriendListFragment friendListFragment = (FriendListFragment)fm.findFragmentById(R.id.friend_list_fragment_container);
LogListFragment logListFragment = (LogListFragment)fm.findFragmentById(R.id.log_list_fragment_container);
后者在前者的onListItemClick事件的上下文中创建。
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
logListFragment = LogListFragment.newInstance(name);
ft.add(R.id.log_list_fragment_container, logListFragment);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
ft.hide(friendListFragment);
}
ft.addToBackStack(null);
ft.commit();
随着onListItemClick每一个电话我先清除返回堆栈,因为我只想对返回堆栈的最新logListFragment。
在onCreate我的活动的功能我关心我的手机的方向。在纵向模式下我清除返回堆栈和通过以下方式重新添加logListFragment:
if ((logListFragment != null) && (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.add(R.id.log_list_fragment_container, logListFragment);
ft.hide(friendListFragment);
ft.addToBackStack(null);
ft.commit();
}
之后,由于预期friendListFragment是隐藏的,而且logListFragment是不可见的。 当我更改代码它按预期工作方式如下:
if ((logListFragment != null) && (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)) {
LogListFragment copy = new LogListFragment();
copy.setArguments(logListFragment.getArguments());
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.add(R.id.log_list_fragment_container, copy); // <- use copy
ft.hide(friendListFragment);
ft.addToBackStack(null);
ft.commit();
}
当我添加LogListFragment它的工作原理的新实例。
问题:
- 为什么我需要创建一个新的实例?
- 有人知道更好的解决方案吗?