Android BottomNavigationView 与闪屏返回堆栈问题
因此,我使用导航组件库设置了我的 BottomNavigationView
(如 此处),一切正常,每个选项卡都可以保留其后堆栈。但是,如果我添加启动屏幕 (Fragment
) 并:
- 将其设置为起始目标(
popUpInclusive
已设置为 true) - 从 SplashFragment 创建操作到第一个选项卡 HomeFragment
然后所有选项卡不再保留其后堆栈,而且导航变得很奇怪:
Splash ->主页(第一个选项卡)->我(第二个选项卡)->首页->按返回,它会返回到“我”,而不是退出应用程序。
PS:我使用带有单个导航图的单个活动模式。
So I setup my BottomNavigationView
(like here) using Navigation Component library and everything works fine, every tab can keep their back stacks. However, if I add a Splash screen (Fragment
) and:
- Set it as start destination (
popUpInclusive
set to true already) - Create action from SplashFragment to the first tab HomeFragment
then all the tabs no longer keep their back stacks, plus the navigation becomes weird:
Splash -> Home (first tab) -> Me (second tab) -> Home -> press back, it goes back to Me instead of exiting the app.
PS: I'm using single Activity pattern with single navigation graph.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,感谢 @ianhanniballake,我在这里发布了我的最终解决方案,关键点是
BottomNavigationView
必须是起始目的地,而不是其他 条件目的地,例如登录或启动屏幕。第 1 步:创建并设置 Splash 布局和片段
将
SplashFragment
添加到导航图中。无需从
HomeFragment
创建操作 ->SplashFragment
,除非你需要过渡动画步骤 2. 设置
MainViewModel
(共享ViewModel
)步骤 3.设置
HomeFragment
第 4 步。设置
SplashFragment
演示:https://youtu.be/AxiIsY6BtGg
Ok, thanks to @ianhanniballake, I post my final solution here, the key point is that the
BottomNavigationView
must be the start destination insead of other conditional destination like login or splash screen.Step 1. Create and Setup Splash Layout and Fragment
Add
SplashFragment
into Navigation graph.No need to create action from
HomeFragment
->SplashFragment
, unless you need transition animationStep 2. Setup
MainViewModel
(sharedViewModel
)Step 3. Setup
HomeFragment
Step 4. Setup
SplashFragment
Demo: https://youtu.be/AxiIsY6BtGg
我按如下方式解决了这个问题:
创建 2 个导航图:
navigation/splash_nav_graph.xml -(这里可能有一个大图,例如授权流程)。
navigation/bottom_nav_graph.xml - 主图 (例如):
activity_main.xml
添加 android:visibility="gone" 以便 BottomNavigationView 在开始时不显示
MainActivity.kt
然后在 SplashFragment(或splash_nav_graph.xml 中的任何其他片段)中,转到主图:
I solved this problem as follows:
Сreate 2 navigation graphs:
navigation/splash_nav_graph.xml - (there may be a large graph here, for example an authorization flow).
navigation/bottom_nav_graph.xml - main graph (by example):
activity_main.xml
add android:visibility="gone" so that BottomNavigationView is not displayed at start
MainActivity.kt
And then in your SplashFragment (or any other fragment in splash_nav_graph.xml), to go to the main graph: