Android Jetpack Navigation component use, jump, parameter transfer, action, rollback, dynamic loading, etc.

table of Contents

1. Introduction

2. Conditions of use

Three, the main components

Fourth, the main function

Five, use

1. Create a Navigation Graph

3. Edit the navigation map and add the destination to the navigation map

4. Connection destination

5. Add NavHostFragment to Activity

6, jump

7, global action

8. Data transfer

9, back

10. Dynamic loading


1. Introduction

Navigation is part of the Jetpack component library and was launched in 2018; it is mainly used for Fragment management and jumps between them, making the single Activity architecture simpler;

2. Conditions of use

1. AndroidStudio version requires 3.2 and above

2. Add dependencies to build.gradle under module, and optionally add dependencies according to the language of your project;

dependencies {
  def nav_version = "2.3.0"

  // Java language implementation
  implementation "androidx.navigation:navigation-fragment:$nav_version"
  implementation "androidx.navigation:navigation-ui:$nav_version"

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

Regarding dependency configuration issues, you can check the official website information: https://developer.android.com/jetpack/androidx/releases/navigation

Official website document address: https://developer.android.com/guide/navigation

The version number of AndroidStudio used in this article is 4.0.1;

Three, the main components

  • Navigation Graph: The navigation graph is an xml resource; created under res/navigation/;
  • NavHostFragment: similar to a container, add Navigation Graph to it;
  • NavController: handle jumps between Fragments (Kotlin / Java objects);

Fourth, the main function

  1. Visual navigation map
  2. Navigate by destination and action
  3. Transition animation
  4. Menu navigation, bottom navigation and menu drawer navigation
  5. Type-safe parameter passing
  6. Deep link

The destination can be understood as Fragment or Activity or another navigation map; sometimes it is also called the target;

Five, use

1. Create a Navigation Graph

Right-click the project new —>Android Resource File, fill in the File name name to customize it here is called navi_graph, Resource type select Navigation, Directory name use navigation;

Note: When adding the navigation map to the project, if the navigation dependency has not been added to the app’s build.gradle file, Android Studio will display a prompt and add the dependency for you.

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navi_graph">

</navigation>
  • <navigation> is the root node of each navigation graph.
  • <navigation> contains one or more destinations represented by <activity> or <fragment>.
  • app:startDestination is an attribute that specifies the default start destination when the user first opens the application. 

In the navigation editor, you can edit the navigation map intuitively or directly edit the XML.

Mainly regardless of:

  1.  "Target" panel: List all targets currently existing in the navigation host and the "Graphics Editor".
  2. Graphic editor: Contains a visual representation of the navigation map. You can switch between the basic XML representation in the "Design" view and the "Text" view.
  3. Properties: Display the properties of the currently selected item in the navigation map.

3. Edit the navigation map and add the destination to the navigation map

Enter the navigation graph navi_graph.xml edit mode, click Split in the upper right corner, a navigation graph is an XML resource file containing all destinations and actions;

The first way

Click to enter New Destination, select Create new Destination to take this as an example; create a Fragment named FirstFragment

The xml resources are as follows 

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:id="@+id/navi_graph"
    app:startDestination="@id/firstFragment">

    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.navigationdemo.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" />
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigationdemo.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" />
    <fragment
        android:id="@+id/thirdFragment"
        android:name="com.example.navigationdemo.ThirdFragment"
        android:label="fragment_third"
        tools:layout="@layout/fragment_third" />

</navigation>

Create a few more Fragments, which will be used later in the jump;

Note: app:startDestination="@id/firstFragment" is similar to MainActivity; the attributes of the fragment tag can be selected by clicking a target, and then modified and set in the "  Properties" panel, or you can edit the XML directly;

The second way

If you have created a new Fragment before, you can click to enter New Destination to find the newly created Fragment. For example, I already have a TestFragment whose layout is fragment_test; here is the layout file name;

4. Connection destination

As mentioned above, a navigation graph also contains an Action tag, which is the logical connection between destinations. It can be under the navigation tag or under the fragment tag; the action tag and the destination attribute indicate the destination and where to jump to There is also an id attribute, which has the same meaning as the id of other controls. It is better to compare and understand; in XML, through the action tag and attribute destination, the id can realize the connection of the target;

Or connect two destinations through the navigation editor:

In the "  Design" tab, hover your mouse to the right of the target you want the user to navigate. A circle will appear above the right side of the target

Click on the circle and drag the mouse to another destination you want to connect to. The result line between the two destinations represents an action;

Click the Text tab to switch to the XML view. Now add action to the source target with id firstFragment. The action has an id and a destination attribute. The value of the destination attribute contains the id of the next destination, as shown in the following example:

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:id="@+id/nav_graph"
    app:startDestination="@id/firstFragment">

    <fragment
        android:id="@+id/firstFragment"
        android:name="com.ang.navigationtest.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/action_firstFragment_to_secendFragment"
            app:destination="@id/secendFragment" />
    </fragment>
    <fragment
        android:id="@+id/secendFragment"
        android:name="com.ang.navigationtest.SecendFragment"
        android:label="fragment_secend"
        tools:layout="@layout/fragment_secend" />
    <fragment
        android:id="@+id/thirdFragment"
        android:name="com.ang.navigationtest.ThirdFragment"
        android:label="fragment_third"
        tools:layout="@layout/fragment_third" />
</navigation>

 Note that to actually navigate to the destination, you still need to write code to perform the navigation. This will jump to the specific description later;

5. Add NavHostFragment to Activity

There are also two ways:

The first way

Write in the activity_main.xml layout of Main Activity ; the specific code is as follows, the name is fixed and cannot be modified, and the navGraph attribute value is

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/nav_host_fragments"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navi_graph"/>

  </androidx.constraintlayout.widget.ConstraintLayout>

app:defaultNavHost="true": Let the Navigation container handle the return event. If there is a page jump in the Navigation container, clicking the return button will first process the return between the Fragment pages in the container, and then process the Activity after processing the page in the container Return of the page. If the value is false, the return of the Activity page is processed directly. Here you can find that the navigation graph has exploded in popularity just now, but now it has disappeared;

The second way:

If your Activity layout uses a constraint layout, in the layout view Split, drag a NavHostFragment in Containers, and then select your own navigation map file; don’t forget to set constraints.

6, jump

To realize the jump between destinations, it is through NavController

There are three main ways to obtain NavController

NavHostFragment.findNavController(Fragment)
Navigation.findNavController(Activity, @IdRes int viewId)
Navigation.findNavController(View

It seems that this is also possible

FragmentManager supportFragmentManager = getActivity().getSupportFragmentManager();
NavHostFragment navHostFragment = (NavHostFragment) supportFragmentManager.findFragmentById(R.id.fragment);
NavController navController = navHostFragment.getNavController();

Then jump through the navigate method of NavController; here resId can be the id of the destination fragment in the navigation graph, or the id of the action of the source and destination;

//navigate方法
public void navigate(@IdRes int resId) {
     navigate(resId, null);
}

The jump can also be achieved as follows

view.findViewById(R.id.btn_to_secend).setOnClickListener( Navigation.createNavigateOnClickListener(R.id.secendFragment, null));

7, global action

As mentioned above, you can also add action under the navigation tag. This is a global action, which can solve multiple source destinations to jump to the same destination. It is not necessary to write the same action in each source destination. It is accurate Said it should be the destination attribute;

8. Data transfer

The navigate jump method of NavController also has an overload method, which has a Bundle parameter, so the data transfer between destinations can be realized through Bundle;

public void navigate(@IdRes int resId, @Nullable Bundle args) {
     navigate(resId, args, null);
}

9, back

Since NavController can realize the jump, the similar function rollback can of course be realized. NavController has navigateUp() and popBackStack() two methods to return to the previous level;

10. Dynamic loading

Navigation can be dynamically loaded in Fragment or Activity:

FragmentManager supportFragmentManager = getSupportFragmentManager();
NavHostFragment navHostFragment = (NavHostFragment) supportFragmentManager.findFragmentById(R.id.fragment);
NavController navController = navHostFragment.getNavController();
navController.setGraph(R.navigation.nav_graph);
NavHostFragment也是一个Fragment;可以当作一个Fragment使用;

Guess you like

Origin blog.csdn.net/ezconn/article/details/108671409