【问题标题】:Navigate up by back button with Navigation Component使用导航组件通过后退按钮向上导航
【发布时间】:2021-04-19 08:00:58
【问题描述】:

我使用导航组件从一个片段导航到另一个片段。但是,当用户按下后退按钮时,我想导航回第一个片段。但它一直显示第二个片段。这是我的导航图:

<?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。

编辑2: 添加了更多代码。

【问题讨论】:

    标签: android android-architecture-navigation


    【解决方案1】:

    您正在使用 LiveData 进行活动。 LiveData 总是缓存设置的值,所以当您返回 Fragment1 时,您会再次观察 LiveData 并再次获得相同的值,导致您再次导航()。

    请参阅this blog post 了解更多信息和替代方案。

    【讨论】:

    • 谢谢,但我已经试过了。结果是当我添加 popUpToInclusive 时应用程序完成。
    • 根据您发布的代码,您的起始目的地是overviewFragment,所以它应该仍然在后堆栈上,对吧?
    • 啊,抱歉弄错了,起始片段是fragment1。当我为 SO 准备 xml 时,我忽略了这一点。我会在帖子中更正。
    • 好的,那么您似乎根本不想要popUpTopopUpToInclusive。你能在你打电话给navigate()的地方包括周围的代码吗?您是在 observe 块内调用它吗?
    • 是的,这是真的,我在观察块中调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2013-12-23
    相关资源
    最近更新 更多