android - 使用显示/隐藏事务保存片段状态是否错误?
问题描述
我有一个带有五个选项卡的 bottomNavigationView,用于在五个片段之间导航用户。我希望一次保存其中四个的状态,例如当用户转到片段 B 并返回片段 A 时,片段 A 应该与他离开时完全相同。首先,我使用了 android 导航组件,但它不支持多栈,所以我将其移除并使用了流行的片段事务。
这是我目前正在做的事情:
- 我的活动中有一个成员变量“activeFragment”,它被初始化为用户在进入活动时看到的主要片段,并在用户导航到另一个片段时更新
当用户导航到一个片段时,我隐藏当前活动片段并显示与单击的选项卡关联的片段(如果该片段尚未创建,我首先创建)使用:
getSupportFragmentManager().beginTransaction().hide(activeFragment).show(toFragment);
它工作得很好,唯一奇怪的行为是片段没有收到通常的生命周期回调,例如当我导航到片段时它不会触发 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());
}
解决方案
仅当内存一次存储 5 个片段是安全的时,这才是好方法。
为了管理生命周期,您可以使用 FragmentTransaction.setMaxLifecycle()
例如:
fragmentManager
.beginTransaction()
.run {
fragmentManager
.fragments
.forEach {
hide(it)
setMaxLifecycle(it, Lifecycle.State.CREATED)
}
show(topFragment)
setMaxLifecycle(topFragment, Lifecycle.State.RESUMED)
}
.commit()
推荐阅读
- nativescript - 迁移到 NativeScript 7
- python - 有人告诉我,python 线程并不意味着我的代码是并行运行的,但确实如此。有人可以解释吗?
- r-markdown - 为什么 blogdown::hugo_build() 不能处理 Lua 过滤器?
- laravel - 如何从嵌套关系中获取特定列 - Laravel
- git - 如何根据我要克隆的 git 存储库来源自动更改我的本地 git config `user.email`?
- shell - 带变量的 curl 不起作用 - Shell 脚本
- linux - 尝试访问结构文件 private_data 时出错
- javascript - 如何在页面上的隐藏元素上使用 jQuery 添加类和删除类
- php - 更改 PHP 收到的 URL(通过 .htaccess?)
- css - CSS Wordpress 联系表格定制