android - Jetpack 导航启动上一个屏幕
问题描述
我有这个由 3 个屏幕组成的简单导航设置:
Screen 1 -> Screen 2 -> Screen 3
|______________________^
屏幕 2 是填写一次即可跳过的注册表单。
我有一个 Jetpack 导航图的奇怪问题,当从屏幕 2 -> 3 导航时,应用程序由于屏幕 1(!)onViewCreated()
激活而崩溃,并且找不到导航方向:
java.lang.IllegalArgumentException: navigation destination
com.example.app:id/action_screen1_to_screen3 is unknown to this NavController
我的导航图:
<fragment
android:id="@+id/screen1"
android:name="Screen1Fragment"
android:label="Screen 1"
tools:layout="@layout/fragment_screen_1">
<action
android:id="@+id/action_screen1_to_screen2"
app:destination="@id/screen2"
app:launchSingleTop="false"/>
<action
android:id="@+id/action_screen1_to_screen3"
app:destination="@id/screen3"
app:launchSingleTop="false"
app:popUpTo="@id/screen1"
app:popUpToInclusive="true" />
</fragment>
<fragment
android:id="@+id/screen2"
android:name="Screen2Fragment"
android:label="Screen 2"
tools:layout="@layout/fragment_screen_2">
<action
android:id="@+id/action_screen2_to_screen3"
app:destination="@id/screen3"
app:launchSingleTop="false"
app:popUpTo="@id/screen2"
app:popUpToInclusive="true" />
</fragment>
<fragment
android:id="@+id/screen3"
android:name="Screen3Fragment"
android:label="Screen 3"
tools:layout="@layout/fragment_screen_3">
</fragment>
我使用的是自动生成的 NavDirections,所以这不是使用错误的资源 ID 的问题。
导航代码:
// Screen 1
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
if (isLoggedIn) {
view?.findNavController()
?.navigate(Screen1FragmentDirections.screen1ToSelectScreen3())
} else {
signInButton.setOnClickListener {
val action =
Screen1FragmentDirections.screen1ToScreen2()
view?.findNavController()?.navigate(action)
}
}
}
// Screen 2
view?.findNavController()?.navigate(Screen2FragmentDirections.screen2ToScreen3())
我的 Gradle 导入:
def nav_version = "2.3.0-alpha04"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
任何帮助表示赞赏,谢谢!
解决方案
不知道为什么会这样,但我找到的解决方案不是 popUpTo 直到当前屏幕,而是 popUpTo 整个导航图:
[...]
app:popUpTo="@id/nav_graph"
app:popUpToInclusive="true"
[...]
推荐阅读
- go - 在模板中使用函数而不是方法
- android - MaterialSearchView + 工具栏 + 地图
- python - 即使成功将 selenium 包安装到 pycharm 也无法运行 selenium 脚本
- asp.net - 如何在MVC中将单个对象和列表对象从视图返回到控制器
- javascript - AJAX 只保存输入的第一个字母
- mongodb - Mongo聚合查找
- c# - TestServer使用真正的sql数据库
- android - Android Studio 上的 Gradle 项目同步失败
- node.js - 快速会话未能持久会话
- java - 为什么这个表情符号正则表达式也匹配数字