1, the introduction of

Navigation simplifies the implementation of Navigation and also helps you visualize the Navigation flow of your application. The Naviagtion component provides the following functions:

  1. Automatic processing of Fragment transactions
  2. The default handles the return key and the previous action
  3. Default behavior for animations and transitions
  4. The default page and the link operation at the next level
  5. Implement navigation interfaces (such as navigation drawer and step navigation) with very little code
  6. Navigation Switching between interface parameter transfer
  7. A visual Navigation interface in Android Studio

1.1 What do you need to do?

In Codelab you can use demo to run effects:

All activities and Fragments are already created for you. You can use the navigation component to connect them and perform the following functions during the connection:

  1. A visual Navigation editor
  2. Design navigation destinations and actions
  3. Switch the animation
  4. Menu Menu, bottom navigation bar, and DrawLayout sidebar button
  5. Type-safe parameter passing
  6. Deep links

1.2 Conditions of use

  • Basic Kotlin knowledge (Kotlin is used in codelab code)
  • Android Studio 3.2 above
  • API 14+

2, an introduction to

2.1 Obtaining the Code

Github

$ git clone https://github.com/googlecodelabs/android-navigation
Copy the code

2.2 summary of Navigation

The Navigation component mainly consists of three parts

  1. Navigation Graph (a new XML file) is a new XML file that contains all the information related to Navigation in one place. It includes all the interfaces (activities or fragments) in the app and the possible paths that the user can access through the app.
  2. NavHostFragment (Layout XML View), which is a special widget added to the Layout. AvHostFragment is associated with the Navigation editor via navGraph.
  3. NavController(Kotlin/Java Object), which is an object that tracks the current position in the navigation diagram and coordinates the exchange of the target contents in the NavHostFragment as you move through the navigation diagram.

As you navigate, you’ll use the navigation controller object and tell it where you want to go, or what path you want to take in your navigation diagram. The navigation controller will then display the appropriate destination in NavHostframent.

That’s the basic idea. Let’s start with the new navigation diagram resource to see what this looks like in practice.

3, Navigation Graph

3.1 Destinations

The Navigation component has the concept of Destinations, which is a destination that can be navigated to anywhere in your APP, usually an Activity or Fragment, which is supported by default and you can customize the target type if you want.

3.2 Navigation Graph

A navigation diagram is a new type of resource that visually shows all destinations that can be reached from a given destination. Shown in the Navigation Editor of AS, here is part of the initial Navigation diagram created for the APP:

3.3 Navigation Editor

  1. Open theres/navigation/mobile_navigation.xmlfile
  2. Click Desgin to enter design mode

action

  1. Click on a target screen to view properties

  1. Click on any of the arrow actions to view the properties

3.4 Navigation XML parsing

Any design changes you make to the navigation in design mode can be seen in the XML layout file by clicking the Text button

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/home_dest">

    <!-- ...tags for fragments and activities here -->

</navigation>
Copy the code

Note:

  • <navigation>The TAB is the layout of the entire view
  • <navigation>Includes one or more target interfaces, typicallyActivityorfragment
  • app:startDestinationIs a special property of the target interface that represents the default page to launch

The following

<fragment
    android:id="@+id/flow_step_one_dest"
    android:name="com.example.android.codelabs.navigation.FlowStepFragment"
    tools:layout="@layout/flow_step_one_fragment"> <argument ... /> <action android:id="@+id/next_action"
        app:destination="@+id/flow_step_two_dest">
    </action>
</fragment> 
Copy the code

Pay attention to

  • android:idIs the ID property of the target interface that you define
  • ndroid:nameIs the entire package pathname for your target interface
  • tools:layoutSpecifies the layout that should be displayed in the graphics editor

The


in the code is described below

Add a target interface to the navigation view

There are only a few targets connected to main in the demo. Now we can add a target interface. First you need to create your own Fragment or Activity:

The code for each step is available in the demo, where you can write the code in TODO or compare it to the commented out code

  1. Open theres/navigation/mobile_navigation.xmlFile, clickDesginbutton
  2. Click the New button and select settingS_Fragment

mobile_navigation.xml

<fragment
    android:id="@+id/settings_dest"
    android:name="com.example.android.codelabs.navigation.SettingsFragment"
    android:label="@string/settings"
    tools:layout="@layout/settings_fragment" />
Copy the code

To follow our naming convention, change the ID from the default SettingsFragment to SettingsFragment

5. Use Navigation Graph to navigate a page

5.1 Interface and Navigation

The Navigation component follows the Navigation guide in Navigation principles, which suggests that you use activities as the entry of your APP. Activities include ordinary Navigation such as BottomNavigation. In contrast, Fragment version 1 acts as a target interface.

Next, you need to add NavHostFragment in layout, NavHostFragment through navGraph associated with navigation navigation editor

<LinearLayout ... /> <androidx.appcompat.widget.Toolbar ... /> <fragment android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:navGraph="@navigation/mobile_navigation"
        app:defaultNavHost="true"/> <com.google.android.material.bottomnavigation.BottomNavigationView ... /> </LinearLayout>Copy the code

Note:

  • This is an Activity that contains a normal Navigation, a bottom Navigation, and a Toobar
  • android:name="androidx.navigation.fragment.NavHostFragment"app:defaultNavHost="true"throughNavHostFragmentConnect system return key
  • app:navGraph="@navigation/mobile_navigation"throughNavHostFragmentConnect the navigation menu button and the navigation view can be passedNavHostFragmentNavigate to any target interface

5.2 NavController

Finally, when you click a button, you need to trigger a navigation command. The Navcontroller triggers a Fragemnt switch in the NavHostFragment.

// Command to navigate to flow_step_one_dest
findNavController().navigate(R.id.flow_step_one_dest)
Copy the code

Note that you enter the target or action ID to navigate, ids that you define in the XML layout. NavController is very powerful. You can call navigate() or popBackStack() to convert code into matching navigation operations based on the type of target you are navigating. For example, you can call navigate() to navigate to a target interface, and NavConroller will call its startActivity().

Kotlin provides an extension function to get the NavController object associated with the NavHostFragment:

  • Fragment.findNavController()
  • view.findNavController()
  • Activity.findNavController(viewId: Int)

Your NavController is associated with a NavHostFragment. So whichever method you use, you must ensure that Fragmengt, View, or View ID is NavHostFragmengt itself, or its parent. Otherwise an exception will be thrown.

5.3 Switching pages using NavController

You can switch FlowStepFragment using NavController

  1. Open theHomeFragment.kt
  2. inonViewCreated()In the findnavigate_destination_button
val button = view.findViewById<Button>(R.id.navigate_destination_button) button? .setOnClickListener { findNavController().navigate(R.id.flow_step_one_dest, null) }Copy the code
  1. Navigate To flow_step_one_dest Destination by running the APP and clicking the Navigate To Destination button. Note that this button navigates To the Flow_Step_one_dest Destination

You can also use the method of convenient Navigation. CreateNavigateOnClickListener (@ IdRes destId: int, bundle: bundle). This method builds an OnClickListener to navigate to the given target and passes it with a set of parameters.

val button = view.findViewById<Button>(R.id.navigate_destination_button) button? .setOnClickListener( Navigation.createNavigateOnClickListener(R.id.flow_step_one_dest, null) )Copy the code

6. Change the transition animation

Each navigate() has a default transition animation

You can override the default transformation and other attributes associated with the call, NavOptions, by including a set. NavOptions uses a Builder mode that allows you to override and set the options you want. There is also a KTX DSL for NavOptions, which you will use. For animated transitions, you can define XML animation resources in the Anim Resources folder and then use these animations for transitions. The application code contains some examples:

6.1 Adding a Custom Transition

Update code to display custom transition animations by pressing the navigation to target button.

  1. Open theHomeFragment.kt
  2. defineNavOptionsAnd pass it tonavigate()callnavigate_destination_button
val options = navOptions {
    anim {
        enter = R.anim.slide_in_right
        exit= R.anim.slide_out_left popEnter = R.anim.slide_in_left popExit = R.anim.slide_out_right } } view.findViewById<Button>(R.id.navigate_destination_button)? .setOnClickListener { findNavController().navigate(R.id.flow_step_one_dest, null, options) }Copy the code
  1. Remove the code added in Step 5 (if it still exists)
  2. Confirming that clicking the “Navigate to Destination” button causes the segment to slide onto the screen, and then pressing the segment causes it to slide off the screen

7. Use actions to navigate actions

7.1 the Actions

The navigation system also allows you to navigate through Actions. As mentioned earlier, the lines shown in the navigation diagram are an intuitive representation of the action.

Action navigation has the following advantages over target navigation:

  • You can visualize the navigation path through the application
  • Actions can contain other associated properties that you can set, such as transform animations, parameter values, and Backstack behavior
  • You can navigate using plug-in security Args, as you’ll see shortly

This is the visualization and XML of the connected operation, flow_step_one_dest and flow_step_two_dest:

<fragment
    android:id="@+id/flow_step_one_dest"
    android:name="com.example.android.codelabs.navigation.FlowStepFragment"> <argument ... /> <action android:id="@+id/next_action"
        app:destination="@+id/flow_step_two_dest">
    </action>
</fragment>

<fragment
    android:id="@+id/flow_step_two_dest"
    android:name="com.example.android.codelabs.navigation.FlowStepFragment">
    <!-- ...removed for simplicity-->
</fragment>
Copy the code

Note:

  • These operations are nested in the target – the target from which you will navigate
  • This operation includes a referenceflow_step_two_destTarget parameters of; This is the ID you want to navigate to
  • The ID of the operation is “next_action”
  • This is another connectionflow_step_two_desttohome_dest:

<fragment
    android:id="@+id/home_dest"
    android:name="com.example.android.codelabs.navigation.HomeFragment". /> <fragment android:id="@+id/flow_step_two_dest"
    android:name="com.example.android.codelabs.navigation.FlowStepFragment"> <argument ... /> <action android:id="@+id/next_action"
        app:popUpTo="@id/home_dest">
    </action>
</fragment>
Copy the code

Note:

  • The same IDnext_actionFor joining actionflow_step_two_desttohome_dest. You can use navigationnext_actionID from eitherflow_step_one_destorflow_step_two_dest. This is an example of how actions provide a level of abstraction and can be navigated to different locations depending on the context. Use the popUpTo property – this action will pop the fragment from the back stack until you arrivehome_dest

7.2 Using Action to Navigate

  1. mobile_navigation.xmlOpen the file in design mode
  2. Drag the arrow fromHead home_desttoflow_step_one_dest

  1. Select the action arrow (blue) to change the properties of the action so that:
  • ID = next_action
  • Convert to Enter = slide_in_right
  • Exit = slide_out_left conversion
  • Pop Enter conversion = slide_in_left
  • Pop Exit transition = slide_out_right

  1. Click the ** text ** TAB mobile_navigation.xml
<fragment android:id="@+id/home_dest". > <action android:id="@+id/next_action"
            app:destination="@+id/flow_step_one"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right" />
Copy the code
  1. Open theHomeFragment.kt
  2. Add a click listenernavigate_action_button HomeFragment.kt
view.findViewById<Button>(R.id.navigate_action_button)? .setOnClickListener( Navigation.createNavigateOnClickListener(R.id.next_action,null))Copy the code

Action allows you to attach NavOptions to the navigation XML file instead of specifying them programmatically.

  1. Ok click navigation to action now navigate to the next screen.

8. Use secure ARGS for navigation

8.1 Secure Args

The navigation component has a Gradle plug-in called Safe Args that generates simple objects and builder classes for type-safe access to parameters specified for targets and operations.

Safe Args allows you to remove code like this when passing values between targets:

val username = arguments? .getString("usernameKey")
Copy the code

Instead, replace it with code that generates setters and getters.

val username = args.username
Copy the code

Because of its type safety, navigation using secure ARGs to generate classes is the preferred way to navigate by action and pass parameters during navigation.

8.2 Pass values using secure ARGS

  1. Open the projectbuild.gradleFile and note the Safe args plugin:

build.gradle

dependencies {
        classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"/ /... }Copy the code
  1. Open theapp/build.gradleFile and note the application of the plug-in:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'androidx.navigation.safeargs'

android { 
   //...
}
Copy the code
  1. Open themobile_navigation.xmlAnd notice howflow_step_one_destParameters are defined in the target
<fragment
    android:id="@+id/flow_step_one_dest"
    android:name="com.example.android.codelabs.navigation.FlowStepFragment"
    tools:layout="@layout/flow_step_one_fragment">
    <argument
        android:name="flowStepNumber"
        app:argType="integer"
        android:defaultValue="1"/> <action... > </action> </fragment>Copy the code

Using the

tag, Safeargs generates a class called FlowStepFragmentArgs.

flowStepNumber
android:name="flowStepNumber"
FlowStepFragmentArgs
flowStepNumber

  1. Open theFlowStepFragment.kt
  2. Comment out the line flowstepfragment.kt shown below
/ Comment out this line // val flowStepNumber = arguments? .getInt("flowStepNumber")
Copy the code

This old code is not type-safe. It is best to use secure ARGS. Update the FlowStepFragment to use the code generated class FlowStepFragmentArgs. This will get the parameters in a FlowStepFragment type safe way:

FlowStepFragment.kt

val safeArgs: FlowStepFragmentArgs by navArgs()
val flowStepNumber = safeArgs.flowStepNumber
Copy the code

8.3 Security Args Direction

You can also use secure args to navigate in a type-safe manner, whether parameters are added or not. You can do this using the generated Directions class

Generate direction classes for each different target by operation. The Directions class contains methods for each action that the target has.

For example, the click listener in navigate_action_buttonHomeFragment.kt can be changed to:

HomeFragment.kt

// Note the usage of curly braces since we are defining the click listener lambda view.findViewById<Button>(R.id.navigate_action_button)? .setOnClickListener{ val flowStepNumberArg = 1 val action = HomeFragmentDirections.nextAction(flowStepNumberArg) findNavController().navigate(action) }Copy the code

Note that in the navigation diagram XML, you can provide defaultValue with one for each parameter. If you don’t, then you have to pass parameters to the action, as shown: HomeFragmentDirections. NextAction (flowStepNumberArg)

9. Use the menu, drawer and bottom navigation to navigate

9.1 NavigationUI and navigation – UI – KTX

The navigation component includes a NavigationUI class and the navigation-UI-ktxkotlin extension. NavigationUI has static methods to associate menu items with navigation destinations, and navigation-uI-ktx is a set of extension functions that do the same. If NavigationUI finds a menu item with the same target ID on the current graph, it configures the menu item to navigate to that target

9.2 Use NavigationUI with the Options menu

One of the easiest ways to use NavigationUI is to simplify the options menu Settings. In particular, NavigationUI simplifies handling the onOptionsItemSelected callback.

  1. Open the MainActivity. Kt

Notice how you already have code bloat in the overflow_menu onCreateOptionsMenu

  1. Open the res/menu/overflow_menu. XML

  2. Update the overflow menu to include settings_dest

overflow_menu.xml

<item
    android:id="@+id/settings_dest"
    android:icon="@drawable/ic_settings"
    android:menuCategory="secondary"
    android:title="@string/settings" />
Copy the code
  1. Open the MainActivity. Kt

  2. OnOptionsItemSelected Handles NavigationUI handles using the onNavDestinationSelected helper method. If a menu item is not to navigation, please use the super. OnOptionsItemSelected

MainActivity.kt

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return item.onNavDestinationSelected(findNavController(R.id.my_nav_host_fragment))
            || super.onOptionsItemSelected(item)
}
Copy the code
  1. Run your application. You should have a feature on the ActionBar menu to navigate to SettingsFragment.

9.3 Configuring the bottom navigation using NavigationUI

The code already contains XML layout code for implementing the bottom navigation, which is why you see the bottom navigation bar. But it doesn’t navigate anywhere.

  1. Open theres/layout/navigation_activity/navigation_activity.xml(H470DP) and click the Text TAB

Notice how the XML layout code in the bottom navigation refers to bottom_nav_menu.xml

Navigation_activity. XML (h470dp)

com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_nav_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:menu="@menu/bottom_nav_menu" />
Copy the code
  1. Open ““res/menu/bottom_nav_menu.xml ‘ ‘Notice that the bottom navigation has two items whose ids match the target of the navigation graph target

bottom_nav_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@id/home_dest"
        android:icon="@drawable/ic_home"
        android:title="@string/home" />
    <item
        android:id="@id/deeplink_dest"
        android:icon="@drawable/ic_android"
        android:title="@string/deeplink" />
</menu>
Copy the code

Let the bottom navigation actually do something with NavigationUI.

  1. Open the MainActivity. Kt

  2. BottomNavigationView: bottomNavigationView, navController: navController

MainActivity.kt

private fun setupBottomNavMenu(navController: NavController) { val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav_view) bottomNav? .setupWithNavController(navController) }Copy the code

9.4 Configuring the navigation drawer using NavigationUI

Finally, let’s use NavigationUI to configure side navigation and navigation drawers, including handling the ActionBar and proper navigation. You’ll see this if you have a large enough screen or if the screen is too short for bottom navigation.

Start by observing that you already have the appropriate layout XML code in your application.

  1. Open theNavigation_activity. XML and navigation_activity. XML (w960dp)

Notice how both layouts contain navigationViews connected to nav_DRAwer_menu. In the tablet version (W960DP), NavigationView is always on the screen. On smaller devices, NavigationView is nested in DrawerLayout.

NavigationView navigation is now implemented.

  1. Open the MainActivity. Kt

  2. Navigationmenu uses the implementation method setupWithNavController(navigationView: navigationView, navController: navController). Notice how the version of this method uses NavigationView instead of a BottomNavigationView.

MainActivity.kt

private fun setupNavigationMenu(navController: NavController) { val sideNavView = findViewById<NavigationView>(R.id.nav_view) sideNavView? .setupWithNavController(navController) }Copy the code

The navigation view menu now appears on the screen, but does not affect the ActionBar.

Setting up the ActionBar requires creating an instance of AppBarConfiguration. Purpose AppBarConfiguration specifies the desired configuration options for the toolbar, collapse toolbar, and action bar. Configuration options include whether the bar must handle drawer layouts and which destinations are considered top-level destinations.

The top-level target is the root target of the application. These destinations do not display an “up” button in the app bar, and they display drawer ICONS if the destination uses a drawer layout.

  1. AppBarConfiguration is created by passing a set of top-level target ids and drawer layouts.

MainActivity.kt

val drawerLayout : DrawerLayout? = findViewById(R.id.drawer_layout)
appBarConfiguration = AppBarConfiguration(
        setOf(R.id.home_dest, R.id.deeplink_dest),
        drawerLayout)
Copy the code

How to determine top-level Destinations Destinations reachable through the global navigation UI, such as bottom navigation or side navigation, are all displayed to the user because they are at the same top level of the hierarchy. As such, they are top destinations. Home_dest and deeplink_dest are in the bottom navigation, and we want the drawer ICONS to be displayed on these two destinations, so they are the top destinations. Note that the starting target is always considered the top-level target. If no top-level target list is specified, the only top-level target is your starting target. You can learn more about AppBarConfiguration in the documentation.

5. Implement setupActionBarWithNavController

MainActivity.kt

private fun setupActionBar(navController: NavController,
                           appBarConfig : AppBarConfiguration) {
    setupActionBarWithNavController(navController, appBarConfig)
}
Copy the code

You should also let NavigationUI handle what happens when you press the up button.

  1. coveronSupportNavigationUpandNavigationUI.navigateUpUse the same callAppBarConfiguration.

MainActivity.kt

override fun onSupportNavigateUp(): Boolean {
    return findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)
}
Copy the code
  1. Run your code. If you open the application in the split screen, there should be a navigation drawer available. The up icon and drawer icon should be displayed at the appropriate time and work properly.

The layout Navigation_activity.xml (H470DP) will be used on the phone in portrait mode. This layout also doesn’t include the navigation drawer, but the bottom navigation, which is why you open the app in a split screen and look at the drawer navigation bar. The reason there are no navigation drawers and bottom navigation layouts is because the Material Design guidelines warn against doing so.

Adding a new destination NavigationView is easy. After using up and back navigation, the navigation drawer simply adds a new menu item.

  1. Open themenu/nav_drawer_menu.xml

9. Add a new menu item settings_dest

nav_drawer_menu.xml

<item
    android:id="@+id/settings_dest"
    android:icon="@drawable/ic_settings"
    android:title="@string/settings" />
Copy the code

10. Deep links to destinations

10.1 Deep Links and navigation

The navigation component also includes deep linking support. Deep linking is a way to jump into the middle of an application’s navigation, whether from an actual URL link or from a notification’s pending intent.

One benefit of using the navigation library to handle deep links is that it ensures that the user launches the correct target (described in the next step) with the appropriate backup heap from other entry points, such as application widgets, notifications, or Web links.

Navigation provides a NavDeepLinkBuilder class to build a Class that PendingIntent takes the user to a specific destination

10.2 Adding a Deep Link

We will use the NavDeepLinkBuilderapp widget to connect to the target.

1. Open the DeepLinkAppWidgetProvider. Kt

Add a PendingIntent to NavDeepLinkBuilder:

DeepLinkAppWidgetProvider

val args = Bundle()
args.putString("myarg"."From Widget");
val pendingIntent = NavDeepLinkBuilder(context)
        .setGraph(R.navigation.mobile_navigation)
        .setDestination(R.id.deeplink_dest)
        .setArguments(args)
        .createPendingIntent()

remoteViews.setOnClickPendingIntent(R.id.deep_link_button, pendingIntent)
Copy the code

Note:

  • setGraphNavigation charts are included.
  • setDestinationSpecify the location of the link.
  • setArgumentsInclude any parameters you want to pass to the deep link.

NavDeepLinkBuilder will start your launcher activity by default. You can override this behavior setComponentName() by passing an activity as a context or by setting an explicit activity class.

  1. Add the Deep Link widget to the home screen. Tap and hold on the home screen to see options for adding widgets

  1. Be sure to press the back button to take you to the Home_Dest destination.

For convenience, you can also call NavController’s createDeepLink() method using Context from the current and navigation diagram of NavController.

10.3 DeepLink Backstack

Use the navigation diagram you pass in to determine the background stack of deep links. If the explicit activity you select has a parent activity, those parent activities are also included.

Generate backstack app:startDestination with the specified destination. In this application, we have only one activity and one level of navigation, so backstack will take you to the home_dest destination.

More complex navigation can include nested navigation diagrams. App :startDestination decides to return the stack at each level of the nested graph. For more information about deep linking and nested graphics, see Principles of Navigation.

Associate a Web link with a target

11.1 elements

One of the most common uses of deep linking is to allow Web links to open activity in your application. Traditionally, you use intent-filter and associate the URL with the activity you want to open.

The navigation library makes this very simple and allows you to map urls directly to targets in the navigation diagram.

Are elements that you can add to the target in the diagram. Each element has one required attribute: app: URI.

In addition to direct URI matching, the following features are supported:

  • No scheme URIs are assumed to be HTTP and HTTPS. For example, www.example.com will match http://www.example.com and https://www.example.com.
  • You can match placeholders for one or more characters using the form {placeholder_name}. The String value of the placeholder is available in the Bundle parameter, which has – keys of the same name. For example, www.example.com/users/{id} will…
  • You can use the.* wildcard to match zero or more characters.
  • The NavController will automatically process the ACTION_VIEW intent and look for matching deep links

11.2 Using add URI-based deep links

In this step, you will add a deep link to www.example.com.

  1. Open the mobile_navigation. XML

  2. Add the element to the deeplink_dest target.

mobile_navigation.xml

<fragment
    android:id="@+id/deeplink_dest"
    android:name="com.example.android.codelabs.navigation.DeepLinkFragment"
    android:label="@string/deeplink"
    tools:layout="@layout/deeplink_fragment">

    <argument
        android:name="myarg"
        android:defaultValue="Android!"/>

    <deepLink app:uri="www.example.com/{myarg}" />
</fragment>
Copy the code
  1. Open the AndroidManifest. XML

  2. Add the nav-graph tag. This ensures that the appropriate Intent filter is generated

androidmanifest.xml

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <nav-graph android:value="@navigation/mobile_navigation" />
</activity>
Copy the code

If you want to know what was generated, you can find the result in the output APK. In the Project View, navigate to App – > Build – > Outputs – > APK – > Debug – > app-Debug.apk Double-click app-Debug.apk to open it in APK Analyzer. Here, you will be able to see the generated AndroidManifest.

  1. Use deep links to launch your application. There are two ways to do this:
  • Use the adb

The adb shell am start - a android. Intent. Action. The VIEW - d "http://www.example.com/urlTest"

  • Navigate through the Google app. You should be able to place www.example.com/urlTest in the search bar and display a disambiguation window. Select navigation Codelab