Navigation Arch 组件:为深度链接传递占位符参数

Navigation Arch Component: Passing placeholder param for deeplink

我正在尝试使用新的导航组件 API v1.0.0-alpha05 实现深层链接功能,但 运行 遇到了问题。

使用 Android Studio 3.3 Canary 7

我的部分 navigation_graph.xml

<fragment
    android:id="@+id/noteDetailFragment"
    android:name="com.myapp.notes.notedetail.NoteDetailFragment"
    android:label="@string/label_note_detail"
    tools:layout="@layout/note_detail_fragment">

    <argument
        android:name="noteId"
        android:defaultValue="0"
        app:argType="integer" />

    <action
        android:id="@+id/action_noteDetail_to_editNote"
        app:destination="@id/editNoteFragment" />

    <deepLink
        android:id="@+id/noteDetailDeepLink"
        app:uri="notesapp://notes/{noteId}" />
</fragment>

AndroidManifest.xml 包含:

    <activity android:name=".presentation.MainActivity">
        <nav-graph android:value="@navigation/navigation_graph" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

我正在用 adb shell am start -a android.intent.action.VIEW -d "notesapp://notes/2" com.myapp.notes

测试我的深层链接

noteId 不存在于 NoteDetailFragmentArgs.fromBundle(arguments).noteIdarguments?.getInt("noteId", 0) 中(在这两种情况下都返回默认值 0

打印出 Bundle 表明它在那里:

[{android-support-nav:controller:deepLinkIntent=Intent { act=android.intent.action.VIEW dat=notesapp://notes/2 flg=0x1000c000 pkg=com.mynotes.notes cmp=com.mynotes.notes.presentation.MainActivity }, noteId=2}]

如果深层链接 uri 为 http://www.mynotes.com/notes/2

,则会出现相同的问题

如何在深度链接时访问 noteId?谢谢!

根据 this issue,从深层链接解析的参数仅作为字符串添加到 arguments 包中。

因此,您应该通过 arguments?.getString("noteId")?.toInt() 检索 noteId,直到该问题得到解决。

此问题已在 android.arch.navigation 1.0.0-alpha09 中修复。

Bug Fixes

Arguments are now properly parsed from deep links as the correct argType instead of always as strings b/110273284

Arch 组件发行说明:https://developer.android.com/jetpack/docs/release-notes

Android 导航库将始终 将占位符参数解析为字符串,除非该类型在导航图中明确声明为参数。

对于 {noteId} 的占位符,通过将参数声明为整数来接收作为整数传递的参数。

<argument
    android:name="id"
    app:argType="integer"
    android:defaultValue="0" />