Jetpack Navigation

1,173 阅读11分钟

blockchain Navigation组件是Google推出的Jetpack的组件之一,Navigation 组件使用导航图管理应用导航。导航图是一种资源文件,其中包含应用的所有目的地和逻辑连接(后者也称为“操作”,用户可以通过执行这些操作从一个目的地导航到另一个目的地)。您可以使用 Android Studio 中的 Navigation Editor 管理应用的导航图。下面我们来介绍它的使用。

一:Navigation的使用

注意:Navigation 组件需要 Android Studio 3.3 或更高版本,并且依赖于 Java 8 语言功能。

1.1 添加依赖

如需在您的项目中添加 Navigation 支持,请向应用app的 build.gradle 文件添加以下依赖项:

def nav_version = "2.3.2"
// Kotlin
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
// Feature module Support
implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

我们需要让Navigation支持Safe Args,以确保类型安全。需要添加如下依赖:
在项目的build.gradle中添加

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

并在app的build.gradle里添加插件

// 支持java的
apply plugin: "androidx.navigation.safeargs"

如果你的项目都是kotlin的代码,那么你可以使用。

// 支持kotlin的
apply plugin: "androidx.navigation.safeargs.kotlin"

1.2 创建导航图

  • 右键点击 res 目录,然后依次选择 New > Android Resource File。此时系统会显示 New Resource File 对话框。
  • 在 File name 字段中输入名称,例如“nav_graph”。
  • 从 Resource type 下拉列表中选择 Navigation,然后点击 OK。 这样就可以在res目录下生成一个navigation目录,并在里面生成一个nav_graph.xml文件
    或者: 我们可以直接在res目录下,直接新建一个navigation目录,并在里面新建一个nav_graph.xml文件,代码如下:
<?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/nav_graph">
</navigation>

该nav_graph.xml文件我们称之为导航图

1.3 Activity中添加导航图

Activity类:NavigationTestActivity

class NavigationTestActivity :AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_navigationtest)
    }
}

activity_navigationtest.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • android:name="androidx.navigation.fragment.NavHostFragment" 通过android:name属性来指定NavHost的实现类的名称。这里是NavHostFragment
  • app:navGraph="@navigation/nav_graph" 通过app:navGraph属性,将NavHostFragment以导航图nav_graph关联起来
  • app:defaultNavHost="true" 设置app:defaultNavHost属性,确保NavHostFragment 会拦截系统返回按钮。
    请注意,只能有一个默认 NavHost

1.4 添加Navigation导航视图的起始目的地

我们在nav_graph.xml文件里添加了两个fragment,一个FragmentOne,一个FragmentTwo,并且指定FragmentOne为startDestination(起始目的地),起始就是第一个显示的页面。代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
    </fragment>
    
    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
    </fragment>

</navigation>
  • app:startDestination 这个的意思是,指定起始的页面。用户打开应用看到的第一个页面。
  • android:id 指定id
  • android:name是指定页面的具体路径,比如上面的是FragmentOne的完整路径
  • tools:layout 这个是指定FragmentOne使用的布局 我们把导航图里定义的每一个页面叫做目的地。并且把app:startDestination指定的那个跳转的目的地叫做起始目的地。

1.5 Navigation跳转 Action

比如我们想要从FragmentOne去跳转到FragmentTwo的时候,这时候我们就用到了action,(action我们也称为操作)代码如下
nav_graph.xml文件的代码:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
        <action
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo"/>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
    </fragment>

</navigation>

action里定义了一个行为的id,还有app:destination定义了跳转的目的地,我们这里是指定了fragmentTwo。表明是action_fragmentone_to_fragmenttwo该行为会执行从FragmentOne跳转到FragmentTwo。
FragmentOne的代码:

class FragmentOne :Fragment(){

    private var mRoot:View?=null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRoot = inflater.inflate(R.layout.fragment_one,container,false)
        val tvClickEnterTwo = mRoot?.findViewById<View>(R.id.tv_click_enter_two)
        tvClickEnterTwo?.setOnClickListener{
            Navigation.findNavController(mRoot!!).navigate(R.id.action_fragmentone_to_fragmenttwo)
        }
        return mRoot
    }
}

// fragment_one.xml的布局代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_click_enter_two"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="第一个Fragment"
        android:gravity="center"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

我们可以看到FragmentOne的代码很简单,里面有个TextView控件,显示着第一个Fragment,TextView点击的时候会调用 Navigation.findNavController(mRoot!!).navigate(R.id.action_fragmentone_to_fragmenttwo) 去执行跳转到FragmentTwo。

  • Navigation.findNavController(view)会获得一个NavController
  • NavController.navigate(R.id.xxxx) 会获得某个View的某个Action。跟我们的布局文件的action对应 上面这样就完成了从FragmentOne跳转到了FragmentTwo。\

当我们有很多地方都会跳转到统一个页面的时候,比如说FragmentOne会跳转到FragmentTwo,FragmentThree也能跳转到FragmentTwo。那这时候我们就可以把跳转到FragmentTwo的action定义为全局操作。代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
    </fragment>

    <action
        android:id="@+id/action_fragmentone_to_fragmenttwo"
        app:destination="@+id/fragmentTwo"/>
</navigation>

// Java代码中执行跳转
tvClickEnterTwo?.setOnClickListener{
   Navigation.findNavController(mRoot!!).navigate(R.id.action_fragmentone_to_fragmenttwo)
}

我们可以把action写到外层级,这样导航图里所有的页面都可以去跳转到该action指定的页面,这个就是定义全局的action。\

上面我们学习到可以通过 Navigation.findNavController(mRoot!!).navigate(R.id.action_fragmentone_to_fragmenttwo)去执行跳转。我们发现跳转主要是通过NavController去完成的,而获取NavController 主要有以下几种方式
Kotlin的方式:

  • Fragment.findNavController()
  • View.findNavController()
  • Activity.findNavController(viewId: Int) Java的方式:
  • NavHostFragment.findNavController(Fragment)
  • Navigation.findNavController(Activity, @IdRes int viewId)
  • Navigation.findNavController(View) 比如上面我们的跳转例子也可以写成
 findNavController().navigate(R.id.action_fragmentone_to_fragmenttwo)
 // 或者是
 mRoot!!.findNavController().navigate(R.id.action_fragmentone_to_fragmenttwo)

如果我们加入了Safe Args,那么我们还可以使用Safe Args进行类型安全的跳转
Safe Args 为生成操作的每个目的地生成一个类。生成的类名称会在源目的地类名称的基础上添加“Directions”。例如,如果我们这里是FragmentOne跳转到FragmentTwo,我们的源目的地名称是FragmentOne,则生成的类的名称为 FragmentOneDirections。所以我们上面的跳转代码还可以写成

val action = FragmentOneDirections.actionFragmentoneToFragmenttwo()
Navigation.findNavController(mRoot!!).navigate(action)

这个就是类型安全的跳转。

1.6 使用DeepLinkRequest导航

您可以使用 navigate(NavDeepLinkRequest) 直接导航到隐式深层链接目的地,也就是我们以前所说的自定义URL使用Scheme方式来跳转。代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
    </fragment>

    <activity
        android:id="@+id/order_activity"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.OrderActivity"
        android:label="order_activity"
        tools:layout="@layout/activity_order">
        <deepLink app:uri="www.ccm.com/order"/>
    </activity>

</navigation>

// 跳转到OrderActivity的监听事件
tvEnterOrder.setOnClickListener {
   val request = NavDeepLinkRequest.Builder.fromUri("http://www.ccm.com/order".toUri()).build()
   findNavController().navigate(request)
}
  • 定义一个FragmentOne,一个OrderActivity,OrderActivity里有个指定一个deepLink
  • deeplink里通过app:uri 属性去指定uri
  • 在FragmentOne里tvEnterOrder点击的时候执行跳转到OrderActivity
  • val request = NavDeepLinkRequest.Builder.fromUri("www.ccm.com/order".toUr…
  • findNavController().navigate(request)通过request去跳转 AndroidMainfest.xml下OrderActivity指定的scheme如下:
 <activity android:name=".ui.navigation.OrderActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="https"/>
        <data android:scheme="http"/>
        <data android:host="www.ccm.com"/>
        <data android:pathPrefix="/order/"/>
    </intent-filter>
</activity>

如上就是deepLink的用法。

1.7 添加转场动画

上面我们实现了跳转,那么如何给跳转添加转场动画,nav_graph.xml的代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
        <action
            app:popEnterAnim="@anim/fade_in"
            app:popExitAnim="@anim/fade_out"
            app:exitAnim="@anim/bottom_out"
            app:enterAnim="@anim/bottom_in"
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo"/>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
    </fragment>

</navigation>
  • app:popEnterAnim跟app:popExitAnim是定义了跳转回来该页面的动画。比如这里是从FragmentTwo回到FragmentOne的时候,FragmentOne的出现是淡入的形式
  • app:enterAnim跟app:exitAnim是定义了跳转到其他页面的动画,比如这里是从FragmentOne跳转到FragmentTwo的时候,FragmentOne执行的动画

1.8 嵌套导航图

我们的导航图(及这里的nav_graph.xml),可以使用添加嵌套的导航图。比如我们在nav_graph.xml添加一个登录的导航图,代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
        <action
            app:popEnterAnim="@anim/fade_in"
            app:popExitAnim="@anim/fade_out"
            app:exitAnim="@anim/bottom_out"
            app:enterAnim="@anim/bottom_in"
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo"/>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
        <action
            android:id="@+id/action_fragmenttwo_to_logingraph"
            app:destination="@+id/login_graph"/>
    </fragment>

    <navigation android:id="@+id/login_graph" app:startDestination="@+id/fragmentLogin">

        <fragment
            android:id="@+id/fragmentLogin"
            android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentLogin"
            android:label="fragment_login"
            tools:layout="@layout/fragment_login">
            <action
                android:id="@+id/action_fragmentlogin_to_fragmentregist"
                app:destination="@+id/fragmentRegist"/>
        </fragment>

        <fragment
            android:id="@+id/fragmentRegist"
            android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentRegist"
            android:label="fragment_regist"
            tools:layout="@layout/fragment_regist">
        </fragment>

    </navigation>

</navigation>
  • <navigation android:id="@+id/login_graph" app:startDestination="@+id/fragmentLogin">我们直接添加了一个登录的导航图嵌套在里面,它的id是login_graph,它的起始目的地是登录页面fragmentLogin。
  • 登录的导航图里包含一个登录页面fragmentLogin和一个注册页面fragmentRegist,登录页面有个action可以跳转到注册页面。
  • <action android:id="@+id/action_fragmenttwo_to_logingraph" app:destination="@+id/login_graph"/>FragmentTwo可以点击跳转到登录部分 当前我们还可以把这个登录的导航图抽离出来,通过include的形式去引用。这样就可以让登录流程的导航图在任何需要的地方被引用。 我们在res->navigation文件夹下创建一个login_graph.xml的文件。代码如下:
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/login_graph"
    app:startDestination="@+id/fragmentLogin">

    <fragment
        android:id="@+id/fragmentLogin"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentLogin"
        tools:layout="@layout/fragment_login"
        android:label="fragment_login">
        <action
            android:id="@+id/action_fragmentlogin_to_fragmentregist"
            app:destination="@+id/fragmentRegist" />
    </fragment>

    <fragment
        android:id="@+id/fragmentRegist"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentRegist"
        tools:layout="@layout/fragment_regist"
        android:label="fragment_regist"></fragment>

</navigation>

接着我们可以在nav_graph.xml里include导航图login_graph.xml。代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
        <action
            app:popEnterAnim="@anim/fade_in"
            app:popExitAnim="@anim/fade_out"
            app:exitAnim="@anim/bottom_out"
            app:enterAnim="@anim/bottom_in"
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo"/>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
        <action
            android:id="@+id/action_fragmenttwo_to_logingraph"
            app:destination="@+id/login_graph"/>
    </fragment>

    <include app:graph="@navigation/login_graph"/>

</navigation>

<include app:graph="@navigation/login_graph"/> 通过app:graph去引用我们的login_graph登录导航图。其他的逻辑不变。

1.9 传递参数

我们在页面跳转的时候,经常需要传递一些参数。Navigation也是支持的,不过通常情况下,强烈建议您仅在目的地之间传递最少量的数据,而不要传递大量数据

1.9.1 在导航图里定义参数

我们可以通过argument在导航图里添加跳转携带的参数,比如我们往FragmentTwo传入name跟age参数。代码如下:

<?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/fragmentOne">

    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
        <action
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo"/>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">

        <argument android:name="name"
            app:argType="string"
            android:defaultValue="old man"/>

        <argument android:name="age"
            app:argType="string"
            android:defaultValue="11"/>

    </fragment>

</navigation>


// FragmentOne中有个按钮点击调转到FragmentTwo
tvClickEnterTwo?.setOnClickListener{
   findNavController().navigate(R.id.action_fragmentone_to_fragmenttwo)
}
  • 通过argument来添加传递的参数
  • android:name="name" 表示传递的参数名
  • app:argType 表示传递的参数类型
  • android:defaultValue表示传递的参数的默认值

Navigation 库支持以下参数类型:

类型app:argType 语法是否支持默认值是否支持 null 值?
整数app:argType="integer"
浮点数app:argType="float"
长整数app:argType="long"是 - 默认值必须始终以“L”后缀结尾(例如“123L”)。
布尔值app:argType="boolean"是 “true”或“false”
字符串app:argType="string"
资源引用app:argType="reference"是:默认值必须为“@resourceType/resourceName”格式(例如,“@style/myCustomStyle”)或“0”
自定义 Parcelableapp:argType="<type>",其中 <type> 是 Parcelable 的完全限定类名称支持默认值“@null”。不支持其他默认值。
自定义 Serializableapp:argType="<type>",其中 <type> 是 Serializable 的完全限定类名称支持默认值“@null”。不支持其他默认值。
自定义 Enumapp:argType="<type>",其中 <type> 是 Enum 的完全限定名称是 - 默认值必须与非限定名称匹配(例如,“SUCCESS”匹配 MyEnum.SUCCESS)。

如果参数类型支持 null 值,您可以使用 android:defaultValue="@null" 声明默认值 null

一般我们都会使用目的地下的这个argument参数。例如上面的fragment下的argument。而当我们如果有某个跳转行为(或者叫操作)下有传递参数的话,那么需要以操作下的优先。例如:

<?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/fragmentOne">
    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
         <action
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo">

            <argument android:name="name"
                app:argType="string"
                android:defaultValue="action name old man"/>

            <argument android:name="age"
                app:argType="string"
                android:defaultValue="action age 11"/>
        </action>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
        
        <argument android:name="name"
            app:argType="string"
            android:defaultValue="old man"/>
            
        <argument android:name="age"
            app:argType="string"
            android:defaultValue="11"/>
    </fragment>
</navigation>

比如上面这个例子,FragmentOne的跳转到FragmentTwo的action下有argument携带参数。而本身FragmentTwo下的也有argument携带参数。那么这时候我们会以action下的为准为优先。及优先级 操作下的>目的地下的

1.9.2 使用bundle传递参数

比如上面的例子,在FragmentOne中传递一个name,一个age给FragmentTwo。FragmentTwo把传递过去的内容显示在文本上 。代码如下:

// FragmentOne的代码
class FragmentOne :Fragment(){
    private var mRoot:View?=null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRoot = inflater.inflate(R.layout.fragment_one,container,false)
        val tvClickEnterTwo = mRoot?.findViewById<View>(R.id.tv_click_enter_two)
        tvClickEnterTwo?.setOnClickListener{
            val bundle = bundleOf("name" to "chencm","age" to "11")
            Navigation.findNavController(mRoot!!).navigate(R.id.action_fragmentone_to_fragmenttwo,bundle)
        }
        return mRoot
    }
}

// FragmentTwo的代码
class FragmentTwo : Fragment(){
    private var mRoot: View?=null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRoot = inflater.inflate(R.layout.fragment_two,container,false)
        val name = arguments?.getString("name")?:""
        val age = arguments?.getString("age")?:""
        val tv_text = mRoot?.findViewById<TextView>(R.id.tv_text)
        tv_text?.text = "name===${name}==age===${age}"
        return mRoot
    }
}
1.9.3 使用 Safe Args 传递安全的数据

如果我们使用了Safe Args插件的话,就可以用Safe Args传递安全的数据。代码如下: 一样,我们需要在导航图里定义argument

<?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/fragmentOne">
    <fragment
        android:id="@+id/fragmentOne"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentOne"
        android:label="fragment_one"
        tools:layout="@layout/fragment_one">
         <action
            android:id="@+id/action_fragmentone_to_fragmenttwo"
            app:destination="@+id/fragmentTwo"/>
    </fragment>

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentTwo"
        android:label="fragment_two"
        tools:layout="@layout/fragment_two">
        
        <argument android:name="name"
            app:argType="string"
            android:defaultValue="old man"/>
            
        <argument android:name="age"
            app:argType="string"
            android:defaultValue="11"/>
    </fragment>
</navigation>

也是FragmentOne点击按钮跳转到FragmentTwo,我们来看下点击跳转的地方是如何使用Safe Args传递安全的数据,代码如下:

tvClickEnterTwo?.setOnClickListener{
   findNavController().navigate(FragmentOneDirections.actionFragmentoneToFragmenttwo(name = "ccm",age = "123"))
}

我们上面讲过Safe Args会自动为每个目的地创建一个Directions类,而对应的action的id会生成一个方法actionFragmentoneToFragmenttwo(),而argument则会作为方法的参数传入。上面就是传递的地方。 接收的地方我们统一可以使用arguments来进行接收,代码如下:

class FragmentTwo : Fragment(){
    private var mRoot: View?=null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRoot = inflater.inflate(R.layout.fragment_two,container,false)
        val name = arguments?.getString("name")?:""
        val age = arguments?.getString("age")?:""
        val tv_text = mRoot?.findViewById<TextView>(R.id.tv_text)
        tv_text?.text = "name===${name}==age===${age}"
        tv_text?.setOnClickListener {
            Navigation.findNavController(mRoot!!).navigate(R.id.action_fragmenttwo_to_logingraph)
        }
        return mRoot
    }
}

arguments?.getString("name")通过getArguments()来获取数据。

1.9.4 导航和返回堆栈

Android 会维护一个返回堆栈,其中包含您之前访问过的目的地。当用户打开您的应用时,应用的第一个目的地就放置在堆栈中。每次调用 navigate() 方法都会将另一目的地放置到堆栈的顶部。点按向上或返回会分别调用 NavController.navigateUp() 和 NavController.popBackStack() 方法,用于移除(或弹出)堆栈顶部的目的地
NavController.popBackStack() 会返回一个布尔值,表明它是否已成功返回到上一个目的地。如果该方法返回 false,说明已经到栈顶了。在点返回按钮,一般会处理该页面finish。

if (!navController.popBackStack()) {
    // Call finish() on your Activity
    finish()
}
1.9.5 popUpTo 和 popUpToInclusive

我们经常有场景,比如A跳转到B,B跳转到C,C想跳回到A。每执行一次导航操作,都会将一个目的地添加到返回堆栈。如果您要通过此流程反复导航,则您的返回堆栈会包含多个集合,其中包含每个目的地(例如 A、B、C、A、B、C、A 等)。为了避免这种重复,您可以在从目的地 C 到目的地 A 的操作中指定 app:popUpTo 和 app:popUpToInclusive,如下例所示:

<?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/fragmentA">

    <fragment
        android:id="@+id/fragmentA"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentA"
        android:label="fragment_a"
        tools:layout="@layout/fragment_a">
        <action
            android:id="@+id/action_a_to_b"
            app:destination="@+id/fragmentB">
        </action>
    </fragment>

    <fragment
        android:id="@+id/fragmentB"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentB"
        android:label="fragment_b"
        tools:layout="@layout/fragment_b">
        
		<action
            android:id="@+id/action_b_to_c"
            app:destination="@+id/fragmentC">
        </action>

    </fragment>

	<fragment
        android:id="@+id/fragmentC"
        android:name="com.example.jetpackdatabindingtestapp.ui.navigation.FragmentC"
        tools:layout="@layout/fragment_c"
        android:label="fragment_c">

        <action
            android:id="@+id/action_c_to_a"
            app:destination="@+id/fragmentA"
            app:popUpTo="@+id/fragmentA"
            app:popUpToInclusive="true"
            />
    </fragment>
    
</navigation>

FragmentA 有个action跳转到FragmentB,FragmentB有个action是跳转到FragmentC,C有action直接跳转回FragmentA。

  • app:popUpTo 是表示导航到A,并且我们会在导航过程中从堆栈中移除 B 和 C
  • app:popUpToInclusive=true 表示我们还会将第一个 A 从堆栈上弹出。请注意,如果您不使用 app:popUpToInclusive,则返回堆栈会包含目的地 A 的两个实例。

二:Navigation的结构

上面我们学习了Navigation的使用,通过使用,我们来总结下Navigation是由哪几部分组成。 导航组件由以下三个关键部分组成

  • 导航图:就是我们写的那个nav_graph.xml文件,我们称之为导航图
  • NavHost:显示导航图中目标的空白容器。导航组件包含一个默认 NavHost 实现 (NavHostFragment)。我们在使用的使用有指定 android:name="androidx.navigation.fragment.NavHostFragment"
  • NavController:在 NavHost 中管理应用导航的对象。主要控制导航之前的跳转切换 导航组件提供各种其他优势:
  • 处理 Fragment 事务。
  • 默认情况下,正确处理往返操作。
  • 为动画和转换提供标准化资源。(页面的转场动画)
  • 实现和处理深层链接。(deeplink)
  • 包括导航界面模式(例如抽屉式导航栏和底部导航),用户只需完成极少的额外工作
  • Safe Args - 可在目标之间导航和传递数据时提供类型安全的 Gradle 插件
  • ViewModel 支持 - 您可以将 ViewModel 的范围限定为导航图,以在图表的目标之间共享与界面相关的数据