What is the Navigation

Description on the official website

Navigation is the interaction that allows users to navigate, enter, and exit different pieces of content in an application. Android Jetpack’s navigation component helps you navigate from simple button clicks to more complex modes like app bars and drawer navigation. Navigation components also ensure a consistent and predictable user experience by following a set of established principles.

Navigation is a set of tools that can visually manage Navigation logic in Android Studio

Of course, the instant attraction is a picture released on the official website

You know the structure of the project at a glance.

Create a Navigation Graph

Take a learning mindset. Follow the Navigation component to create your first Navigation diagram

Add the dependent

The latest version 2.3.2 can be downloaded from the English version of the official website. Chinese documents are always slower.

dependencies {
  def nav_version = "2.3.2"

  // Kotlin
  implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
  implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

}
Copy the code

Create the map XML file

Select RES in the module you want to create to create the Android Resource File

In the pop-up window. Set the name. Select Navigation to create a developer set Navigation chart under RES/Navigation

Add the navigation diagram to the layout

Create a normal Activity and create an XML for it. Add FragmentContainerView to its XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  .>
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
Copy the code

The FragmentContainerView here is a container that holds the content. I remember looking at the website before and using the

tag. Don’t worry too much. Mainly look at the internal parameters

  • android:id

This one knows what to do. One thing to note is that you definitely need to bring it. If you forget to add id. An error will be thrown

Caused by: java.lang.IllegalStateException: FragmentContainerView must have an android:id to add Fragment androidx.navigation.fragment.NavHostFragment
Copy the code
  • android:nameProperty contains the class name of the NavHost implementation.
  • app:navGraph Property to associate a NavHostFragment with a navigation diagram
  • app:defaultNavHost="true"Make sure that yourNavHostFragmentIntercepts the system back button. Note that there can only be one default NavHost.

Enrich the navigation diagram

Why do you use the word enrichment? You know that if you’ve done navigation diagrams or other types of flowcharts. Flowcharts provide a variety of tools for you to draw the flowcharts you need on the canvas they provide. Navigation works the same way. It gives the developer a canvas (Navigation Graph) and it’s up to the developer to figure out how to use it. The creation mode can be added by creating a new way. You can use what you already have. Add to the canvas with a Navigation Graph. That’s why we use the word enrichment.

Let’s first look at how to add a shortcut using Navigation Graph. Click on our new navigation diagram. Select Either Splite or Design mode to see a small add icon.

Click on the little icon. You can click to Create your own desination, and of course you can directly select the one you already created. For example, I created my own Fragment

For example, IF I add a HomeFragment to (Navigation Graph)

XML Field Meaning

Let’s look at the generated XML.
is the root node of the navigation graph, android:id=”@+id/nav_graph” is the XML name we created. This is all automatic after the developer creates the XML. What happens when you add a HomeFragment? First, add a

tag. The Android :lable field under the

tag contains the name of the XML layout file for that destination. The Android: ID field contains the ID of the destination, which is used to reference the destination in your code. Don’t worry too much about that either. The development tools do it for us at creation time. You can also see this information in the Design panel


See a startDestination attribute under the
tag. This property represents the current Navigation map, will display that screen, and Navigation is nice enough to add a small house.

Show preview images

Some friends found out. Google’s navigation images can be previewed. None created by yourself can be displayed. Bad review. Don’t worry. Add a Layout field to the < Fragment > TAB to display the preview

Normal forward refers to parameter transmission

Create jump behavior

It’s all built navigation charts. Let’s learn how to jump between interfaces. On the Design TAB, hover the mouse over the right side of the destination, a circle appears above the right side of the destination, click the destination you want the user to navigate to, drag the cursor over the destination, and then release. The lines generated between the two destinations represent operations

Once you’ve done that. XML generates an

tag under the fragment of the origin, where app:destination indicates the destination

Switch to Design mode by clicking on the connection line between. You can also see detailed information.

No arguments to jump

  • Fragment.findNavController().navigate(ResId)
// Click the event
btnAction(R.id.btn_nav_ordinary) {
    / / ordinary jump fragments. FindNavController
    findNavController().navigate(R.id.action_homeFragment_to_logInFragment)
}
Copy the code
  • View.findNavController().navigate(ResId)
// Click the event
btnAction(R.id.btn_nav_ordinary) {
    // Normal jump view.findNavController
    it.findNavController().navigate(R.id.action_homeFragment_to_logInFragment)
}
Copy the code
  • Activity.findNavController().navigate(ResId)
// Click the event
btnAction(R.id.btn_nav_ordinary) {
    / / ordinary jump Activity. FindNavController
    findNavController().navigate(R.id.action_homeFragment_to_logInFragment)
}
Copy the code

The resId is the ID in the < Action > tag we created above

With reference to jump

Not recommended. Not recommended. Not recommended. For the recommended methods, see the Safe Ages Forward Parameter Transfer section

// Click the event
btnAction(R.id.btn_nav_args) {
    // The bundle is normally used to pass parameters
    val bundle = Bundle()
    bundle.putString("user_name"."allens")
    bundle.putInt("user_age".16)
    findNavController().navigate(R.id.action_homeFragment_to_logInFragment, bundle)
}
Copy the code

Retrieve arguments as before Fragment.

// Generally accepted
Log.i("allens-tag"."Use Bundle user_name:${arguments? .get("user_name")}")
Log.i("allens-tag"."Use Bundle user_age:${arguments? .get("user_age")}")
Copy the code

Safe Ages Indicates parameter transfer

Compared with the above jump parameter way. Safe ages are safer and more reliable. Learn how to use it in this section. And why he’s safer and more reliable.

configuration

Safe Ages to see how to use them. Follow the instructions described in Transferring secure Data with Safe Args. To add the plugin

buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.3.2"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"}}Copy the code

Latest version view English version, Chinese version update is not timely

Then add the plugin to the build.gradle file of your application or module

apply plugin: "androidx.navigation.safeargs"
Copy the code

To generate Kotlin language code for Kotlin only modules, add the following line

apply plugin: "androidx.navigation.safeargs.kotlin"
Copy the code

No arguments to jump

Clean rebuild after the configuration is complete. Generates {module} / build/generated/source/navigation – args / {debug} / {said} / {fragments} Dircetions such a file. The file name suffix is Directions

Then use the Directions class that the plug-in created for us

// Click the event
btnAction(R.id.btn_nav_ordinary) {
    / / safe args jump
    val action = HomeFragmentDirections.actionHomeFragmentToLogInFragment()
    findNavController().navigate(action)
}
Copy the code

With reference to jump

In Design mode, click on the layout information in the inspiration location and see it turn blue. See Arguments on the right panel

Click the plus sign to create the parameters you want to pass. The supported parameter types are also described on the official website.

Two fields are created. You can also see the name age information in the navigation diagram

Android :defaultValue is the defaultValue. Android :name indicates the parameter name app:argType indicates the parameter type app:nullable indicates whether the flag is nullable

Again, clean rebuild once you’re done. The plugin will give us a class that ends in Args.

// Pass parameters
// Click the event
btnAction(R.id.btn_nav_ordinary) {
    val bundle = HomeFragmentArgs("River ocean".22).toBundle()
    findNavController().navigate(R.id.action_homeFragment_to_logInFragment, bundle)
}
Copy the code
// Get parameters

Method 1: Use fromBundle
val bundle = arguments
if (bundle ! =null) {
    val homeArgs = HomeFragmentArgs.fromBundle(bundle)
    Log.i("allens-tag".Use safe args user_name:${homeargs.name})
    Log.i("allens-tag".Use safe args user_age:${homeargs.age})}// Approach 2: delegate
val args by navArgs<HomeFragmentArgs>()
Log.i("allens-tag".Use safe args navArgs user_name:${args. Name})
Log.i("allens-tag"."Use safe args navArgs user_age:${args.)
Copy the code

Focus on the blackboard

Why is it safe first? Because it’s very possible to make a mistake if you write name, age, etc., by hand, you put it in the compiler. In this way, there will be no manual errors.

Wait!! . FindNavController ().navigate(R.i.A.ction_homeFragment_to_loginFragment, bundle) Are you sure? You can write your ID right

Eumm??? Hit the face too fast.

It’s not that there’s no solution here. It is clear from the example on the official website that the plugin generates parameters for us. And what we produce doesn’t.

Here you are. I often try to find out. The original parameters are filled in at the revelation location for comparison. I’m going to create a parameter size at the destination location of type String

Rebuild it. If that’s what we expect. Generates a LogInFragmentArgs for us at this point. Look at HomeFragmentDirections, the class we originally generated. Will be found. Changed!

It can be used joyfully at this point

/ / jump
val action = HomeFragmentDirections.actionHomeFragmentToLogInFragment("A lot")
findNavController().navigate(action)
Copy the code
// Accept arguments
val bundle = arguments
if (bundle ! =null) {
    // Notice that it is now LogInFragmentArgs
    val args = LogInFragmentArgs.fromBundle(bundle)
    Log.i("allens-tag"."Safe args size:${args. Size}")
}

val args by navArgs<LogInFragmentArgs>()
Log.i("allens-tag"."Safe args navArgs size:${args. Size}")
Copy the code

Well, it’s really safe now. There’s no problem with the id being written wrong. Sage AGRs is really secure

Deep Links

Deep links are links that take users directly to specific destinations within the app

Let me give you an example. A wechat notification has arrived. Click the notification to jump to the chat screen.

Explicit deep linking

I’m still putting links on the website to create explicit deep links

btn_action_link.setOnClickListener {

        val bundle = Bundle()
        bundle.putString("link_info"."Explicit deep linking")

        val pendingIntent = NavDeepLinkBuilder(this)
            .setGraph(R.navigation.nav_graph)
            .setDestination(R.id.errorFragment)
            .setArguments(bundle)
            .createPendingIntent()


        / / notice
        val notificationManager =
            getSystemService(NOTIFICATION_SERVICE) as (NotificationManager)
        createNotificationChannel()

        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Title")
            .setContentText("Content")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setSmallIcon(R.drawable.placeholder)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
        notificationManager.notify(1, builder.build())
    }
Copy the code

Create implicit deep links

Create implicit deep links

It’s also easy to use. Create a deep link first

To enable implicit deep linking, you must also add content to your application’s manifest.xml file. Add a
element to the Activity pointing to an existing navigation graph

The navigation diagram is created

// Use it
btn_action_hint_link.setOnClickListener {
    val id = "10001"
    findNavController(R.id.nav_host_fragment).navigate("http://www.allens.com/users/${id}".toUri())
}
Copy the code

Add animation effects

The section on adding shared element transitions between destinations gives a nice screenshot

This can be seen on the Design panel

The corresponding XML

Its meaning author also made a schematic diagram simply.

Welcome jumps to the Abort interface

Abort returns to the Welcome interface

reference

[Navigation with Jetpack] Go where you want, compass of Android world