Android Jetpack导航:从“非导航”片段导航

时间:2020-10-29 09:17:22

标签: android android-fragments android-jetpack android-jetpack-navigation

我在我的应用程序中使用了Jetpack Navigation,现在遇到了一种我不完全了解的情况。 我有一个片段CouponFragment,该片段应该在多个地方使用(通过静态xml标签在其他片段内以及在不连接到navGraph的bottomSHeetDialog内)。我需要这个片段才能导航到WebviewFragment,这是navGraph中的目标。 我添加了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>

这有效。当我尝试从CouponFragment内部的BottomSheetFragmentDialog导航时,真正的问题来了。我尝试将一个操作添加到与导航连接的片段中,该片段调用该对话框:

<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

只是看看会发生什么而没有做。没有记录日志。

有人可以提示如何解决此问题吗?

1 个答案:

答案 0 :(得分:1)

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

要从非导航片段导航:

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

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

例如:

  • 具有嵌套的Non-Navigation-FragmentY的FragmentA
  • FragmentB

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