使用导航组件通过后退按钮向上导航 [英] Navigate up by back button with Navigation Component

查看:35
本文介绍了使用导航组件通过后退按钮向上导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use navigation components to navigate from one fragment to another. However, when the user press the back button, I want to navigate back to first fragment. But it keep showing the second fragment. This is my nav_graph:

<?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 的代码中触发导航的方式:

And this is how I trigger the navigation in the code of my 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.

Corrected startDestination in XML.

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

推荐答案

您正在为事件使用 LiveData.LiveData 总是缓存设置的值,所以当你返回到你的 Fragment1 时,你再次观察 LiveData 并第二次获得相同的值,导致你再次导航().

You're using a LiveData for an event. LiveData always caches the set value, so when you return to your Fragment1, you observe the LiveData again and get the same value a second time, causing you to navigate() yet again.

请参阅此博客发布以获取更多信息和替代方案.

See this blog post for more information and alternatives.

这篇关于使用导航组件通过后退按钮向上导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆