Android底部导航-维护活动状态 [英] Android Bottom Navigation - Maintaining Activity State
问题描述
我知道在使用Bottom Navigation
时,建议使用Fragments
而不是Activities
.由于当前的设计,我想避免不得不转换所有Activities
I know it's recommended to use Fragments
instead of Activities
when working with Bottom Navigation
. Due to the current design, I want to avoid having to convert all the Activities
设计:
我正在使用显示的Bottom Navigation
栏
The Design:
I am using a Bottom Navigation
bar like shown
每个选项卡都是一个Activity
.当您点击任意一个选项卡时,它将启动活动startActivity(new Intent(getApplication(), TabActivityName.class));
.问题是,当您在这些选项卡之间切换时,Activity
的状态会丢失.
Each tab is an Activity
. When you tap on any of the tabs, it launches the activity, startActivity(new Intent(getApplication(), TabActivityName.class));
. The problem is that when you switch between these tabs, the state of the Activity
is lost.
例如:
- 单击音乐"选项卡(显示艺术家列表)
- 在音乐"选项卡中单击艺术家,以显示唱片目录
fragment
. - 切换到视频"标签
- 切换回音乐"选项卡. (我希望仍然显示艺术家的
discographyFragment
,但又回到了艺术家的主要列表fragment
)
- Click on the Music tab (Shows a list of artists)
- Click on an artist in the Music tab to show the Discography
fragment
. - Switch to the Video tab
- Switch back to the Music tab. (I want the Artist's
discographyFragment
to still be showing, but it is back at the main List of Artistsfragment
)
我尝试过的事情:
- 将选项卡
Activities
分别更改为android:launchMode="singleTask"
和android:alwaysRetainTaskState="true"
,仅当您切换到在当前activity
之前启动的选项卡时,此选项才会保留数据. - 将每个选项卡
Activities
分别更改为android:launchMode="singleInstance"
和android:alwaysRetainTaskState="true"
,但这会产生创建多个应用程序选项卡的不良后果.
- Changing each of the tab
Activities
toandroid:launchMode="singleTask"
andandroid:alwaysRetainTaskState="true"
This only preserves data if you are switching to tabs that were started before the currentactivity
. - Changing each of the tab
Activities
toandroid:launchMode="singleInstance"
andandroid:alwaysRetainTaskState="true"
But this creates an undesired effect of creating multiple application tabs.
关于如何保持Activity
的状态以及切换选项卡时加载哪个Fragment
的其他任何想法?
Any other ideas on how to maintain the state of the Activity
and which Fragment
is loaded when switching tabs?
推荐答案
您可以使用 FragmentStatePagerAdapter .但是,您应该更新到片段,它们专门用于处理您的情况.迁移还算不错,大多数逻辑都可以简单地复制过来.
You could use FragmentStatePagerAdapter in the Activities. However, you should update to fragments, they are designed to handle your situation. The migration is not that bad, most of the logic can simply be copied over.
这篇关于Android底部导航-维护活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!