首页 > 解决方案 > 使用显示/隐藏事务保存片段状态是否错误?

问题描述

我有一个带有五个选项卡的 bottomNavigationView,用于在五个片段之间导航用户。我希望一次保存其中四个的状态,例如当用户转到片段 B 并返回片段 A 时,片段 A 应该与他离开时完全相同。首先,我使用了 android 导航组件,但它不支持多栈,所以我将其移除并使用了流行的片段事务。

这是我目前正在做的事情:

它工作得很好,唯一奇怪的行为是片段没有收到通常的生命周期回调,例如当我导航到片段时它不会触发 onResume ,当我按下主页按钮并返回活动时,所有片段都会收到' onResume' 这有点尴尬。

那么,这是一种安全的方法吗?有更好的方法吗?鉴于许多实现此功能的应用程序,甚至他们的 google play 商店应用程序都实现了它,为什么 android 没有开箱即用的方式来做到这一点?

编辑:这就是我在片段之间导航的方式:

    private void moveToFragment(MenuItem fragmentNavItem) {
    //Get toFragment given its id
    int id = fragmentNavItem.getItemId();
    FragmentManager fragmentManager = getSupportFragmentManager();
    String tag = getFragmentTagFromItemId(id);
    Fragment toFragment = fragmentManager.findFragmentByTag(tag);

    FragmentTransaction transaction = fragmentManager.beginTransaction();

    transaction.hide(activeFragment);
    if (toFragment == null) {
        //We go to this fragment for the first time
        toFragment = createFragmentFromItemId(id);
        transaction.add(R.id.frame_layout_main, toFragment, tag);
    } else {
        //We have been in this fragment before
        transaction.show(toFragment);
    }

    transaction.commit();

    activeFragment = toFragment;
    toolbar.setTitle(fragmentNavItem.getTitle());
}

标签: androidandroid-fragmentsfragmentbottomnavigationviewfragmenttransaction

解决方案


仅当内存一次存储 5 个片段是安全的时,这才是好方法。

为了管理生命周期,您可以使用 FragmentTransaction.setMaxLifecycle()

例如:


  fragmentManager
      .beginTransaction()
      .run {
          fragmentManager
              .fragments
              .forEach {
                  hide(it)
                  setMaxLifecycle(it, Lifecycle.State.CREATED)
               }
                    
           show(topFragment)
           setMaxLifecycle(topFragment, Lifecycle.State.RESUMED)
         }
      .commit()

推荐阅读