首页 > 解决方案 > Android Jetpack Navigations:从“非导航”片段导航

问题描述

我在我的应用程序中使用 Jetpack Navigation,我现在遇到了一个我不完全理解的情况。我有一个CouponFragment应该在多个地方使用的片段(在其他片段中通过静态 xml 标记和未连接到 navGraph 的 bottomSHeetDialog 内部)。我需要这个片段能够导航到WebviewFragmentnavGraph 中的目的地。我添加了导航条目CouponFragment

在最简单的情况下(CouponFragment在另一个导航连接的片段中),解决方案非常简单,我向包含的片段添加了一个动作CouponFragment,例如:

<fragment
        android:id="@+id/navigation_results"
        android:name="ResultsFragment"
        tools:layout="@layout/fragment_results">
        <action
            android:id="@+id/action_webview"
            app:destination="@id/navigation_webview" />
    </fragment>

这行得通。当我尝试从中导航时,真正的问题出现CouponFragmentBottomSheetFragmentDialog. 我尝试向调用对话框的导航连接片段添加一个操作:

<fragment
        android:id="@+id/navigation_profile"
        android:name="ProfileFragment"
        android:label="@string/title_profile"
        tools:layout="@layout/fragment_profile">
        <action
            android:id="@+id/action_webview"
            app:destination="@id/navigation_webview" />
    </fragment>

但这会导致此异常:

java.lang.IllegalArgumentException: Navigation action/destination package.name:id/action_webview cannot be found from the current destination Destination(package.name:id/navigation_webview) class=WebViewFragment

这很奇怪,因为看起来像是在搜索目标片段上的动作。我尝试添加action_webview一个navigation_webview

只是想看看会发生什么,什么都没有。不打印日志。

任何人都可以提示如何解决这个问题吗?

标签: androidandroid-fragmentsandroid-jetpackandroid-jetpack-navigation

解决方案


我将开始回答主要问题,只是因为细节非常模棱两可,如有必要,请进行编辑。

从 non_navigation 片段导航:

  1. 使用深层链接,这里是文档:https ://developer.android.com/guide/navigation/navigation-deep-link

  2. 只需使用 ParentFragmentDirections 和当前的 NavController。

例如:

  • 带有嵌套非导航片段Y的片段A
  • 片段B

从 FragmentY 导航到 FragmentB 只需从 MainNavigationHostFragment 加载 NavController 并设置为目标“FragmentADirections.actionFragmentA_to_FragmentB()”


推荐阅读