android - 使用导航组件通过后退按钮向上导航
问题描述
我使用导航组件从一个片段导航到另一个片段。但是,当用户按下后退按钮时,我想导航回第一个片段。但它一直显示第二个片段。这是我的导航图:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/fragment1">
<fragment
android:id="@+id/fragment2"
android:name="com.myapp.ui.fragments.Fragment2"
android:label="fragment_2" />
<fragment
android:id="@+id/fragment1"
android:name="com.myapp.ui.fragments.Fragment1"
android:label="fragment_1">
<action
android:id="@+id/action_fragment1_to_fragment2"
app:destination="@id/fragment2"
app:enterAnim="@anim/fragment_fade_enter"
app:exitAnim="@anim/fragment_fade_exit"
app:popUpTo="@id/fragment1" />
</fragment>
</navigation>
这就是我在 Fragment1-Class 的代码中触发导航的方式:
viewModel.itemSelected.observe(viewLifecycleOwner) {
navigate(it)
}
……
fun navigate(id: Long){
val bundle = Bundle()
bundle.putLong("itemid", id)
getNavController().navigate(R.id.action_fragment1_to_fragment2, bundle)
}
编辑: 更正了 XML 中的 startDestination。
Edit2: 添加了更多代码。
解决方案
您正在将 LiveData 用于事件。LiveData 始终缓存设置的值,因此当您返回 Fragment1 时,您再次观察 LiveData 并再次获得相同的值,导致您再次导航()。
有关更多信息和替代方案,请参阅此博客文章。
推荐阅读
- asp.net-core - 什么替代了 ASP.NET Core 中的 SynchronizationContext?
- python - 在使用 opencv 进行视觉特征提取之前,是否应该将图像大小调整为相同?
- c# - 是否可以将应用程序从 Visual Studio 部署到 Azure VM(Windows 10)?
- php - 如何在 Woocommerce 中更新优惠券代码对象
- java - 生成签名的 apk/bundle 时任务 ':app:transformClassesAndResourcesWithR8ForRelease' 执行失败
- python - 如何使用 UNION 语句在 python 中合并两个 SQLite 表(当前出现“ValueError: parameters are of unsupported type”错误消息)
- python - 信号处理程序必须是 signal.SIG_IGN、signal.SIG_DFL 或可调用对象
- c - 同时使用 malloc 和 FILE 指针时出错
- python-3.x - 是否可以在不使用硬件适配器的情况下直接使用 UART 与自动售货机(使用 MDB)进行通信?
- python - 如何让 lxml 将两个页面保存到页面中,以便树可以读取它?