Android Jetpack Navigation storing deepLink as constants

Viewed 199

The Android documentation recommends using deep links for inter-module navigation. https://developer.android.com/guide/navigation/navigation-multi-module#across

Note the deeplink with the following:

app:uri="android-app://example.google.app/fragment_two"

The same url is then referenced in code:

val request = NavDeepLinkRequest.Builder
    .fromUri("android-app://example.google.app/fragment_two".toUri())
    .build()

The example is clear, but it uses hard-coded strings, which should best be stored in one location. I could use a string resource, like this:

// values/strings.xml
<string name="fragment_two_url">android-app://example.google.app/fragment_two/</string>

// nav_graph.xml
app:uri="@string/fragment_two_url"

// Kotlin code
val request = NavDeepLinkRequest.Builder
    .fromUri(context.getString(R.string.fragment_two_url))
    .build()

however this won't work if the deep link has arguments, like this:

app:uri="android-app://example.google.app/fragment_two/{arg}"

We cannot insert the string resource like we did above.

// This won't work
app:uri="@string/fragment_two_url/{arg}"

Is there a way to create a constant that could easily be referenced in both the Kotlin code and navigation graph XML?

1 Answers

see the following from Format and style

<string name="url_with_args">android-app://example.google.app/fragment_two/%s</string>

and then use it like this:

val finalUrl = context.getString(R.string.url_with_args, "Your_Argument")

Related