从背面弹出片段,然后再次添加



我有两个片段friendListFragmentlogListFragment

    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的新实例时,它就可以工作了。

问题

  1. 为什么我需要创建一个新实例
  2. 有人知道更好的解决方案吗

也许替换碎片是更好的选择?

ft.replace(int containerViewId,Fragment Fragment)

相关内容

最新更新