簡體   English   中英

使用 arguments 的多模塊 android 架構中的導航

[英]Navigation in multi-module android architecture with arguments

由於導航文件位於 app 模塊中,因此功能模塊無法訪問 Args 文件。 有什么解決方法嗎?

例如:如果我有一個接受 email 和密碼的片段,就像這樣

<fragment
        android:id="@+id/navigation_sample"
        android:name="SampleFragment">
        <argument
            android:name="email"
            app:argType="string" />
        <argument
            android:name="password"
            app:argType="string" />
    </fragment>

我會生成一個可用於導航的 SampleFragmentArgs

findnavController.navigate(R.id.navigation_sample, SampleFragmentArgs(email, password).toBundle)

但是我只能從應用程序模塊而不是功能模塊中使用它

這取決於您所說的“功能模塊”,但是我假設應該是 android 庫。

這是有效的設置:

  1. 假設您的 android 庫稱為“mylibrary”
  2. 您的“應用程序”模塊自然應該具有以上作為依賴項
  3. 您的“mylibrary”應該有apply plugin: "androidx.navigation.safeargs.kotlin"和庫頂級 build.gradle 的類路徑中的相應設置
  4. 讓我們在庫中聲明導航圖(例如,mylibrary_graph.xml,id 為 myLibraryGraph),就像您在“app”模塊中所做的那樣 - 假設它以您的“SampleFragment”為起點,列出所有這些 arguments。
  5. 假設您的“app”模塊有一些導航圖,讓我們將“mylibrary_graph.xml”嵌套在那里( <include app:graph="@navigation/mylibrary_graph" />
  6. 假設您的“應用程序”模塊導航圖有一些片段需要跳轉到 android 庫中的“SampleFragment”。 我們將像這樣聲明它(偽代碼):
    <fragment
        android:id="@+id/HelloWorldFragment"
        android:name="..."
        android:label="..."
        tools:layout="...">

        <action
            android:id="@+id/jumpToSampleFragment"
            app:destination="@+id/myLibraryGraph">

          <argument
              android:name="email"
              app:argType="string" />
          <argument
              android:name="password"
              app:argType="string" />
        </action>
    </fragment>
  1. 最后,您可以在 HelloWorldFragment 中執行此操作: findNavController().navigate(HelloWorldFragmentDirections.jumpToSampleFragment("oh@acme.com", "nimda"))

正如人們所看到的,它可以工作,但是在 2 個地方聲明 arguments 有點不便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM