【问题标题】:Android Jetpack Navigations: navigate from "non-navigation" fragmentAndroid Jetpack Navigation:从“非导航”片段导航
【发布时间】:2020-10-29 09:17:22
【问题描述】:

我在我的应用程序中使用 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>

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

<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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    从非导航片段导航:

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

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

    例如:

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

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

    【讨论】:

    • 这是有道理的。如果有任何帮助,我会尝试并接受。您能否指出您在问题中发现的模棱两可之处,以便我改进?
    • 目前还不清楚你有多少导航图和主机片段;此 nn 导航片段的嵌套方式,或者包装器底部工作表对话框片段是否是导航图中的对话框目标。您实际上可以避免使用特定名称,而只是提出您尝试实现的导航方案
    猜你喜欢
    • 1970-01-01
    • 2020-07-05
    • 2021-12-23
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多