2.nav_graph.xml:声明导航结构图
NavGraphFragment作为Activity导航的 容器 ,然后,其 app:navGraph 属性指向一个navigation_graph的xml文件,以声明其 导航的结构。
NavGraphFragment在 获取 并 解析 完这个xml资源文件后,它首先需要知道的是:
类似APP的home界面,NavGraphFragment首先要导航到哪里?
<?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" app:startDestination="@id/page1Fragment"> <fragment android:id="@+id/page1Fragment" android:name="com.qingmei2.samplejetpack.ui.main.MainPage1Fragment" android:label="fragment_page1" tools:layout="@layout/fragment_main_page1"> <action android:id="@+id/action_page2" app:destination="@id/page2Fragment" /> </fragment> //省略...</navigation>
在navigation的根节点下,我们需要处理这样一个属性:
app:startDestination=“@id/page1Fragment”
Destination 是一个很关键的单词,它的直译是 目的地。 app:startDestination属性便是声明这个id对应的 Destination 会被作为 默认布局 加载到Activity中。这也就说明了,为什么我们的sample,默认会显示 MainPage1Fragment。
现在,我们的app默认展示了MainPage1Fragment, 那么接下来,我们如何实现跳转逻辑的处理呢?
3.Action标签:声明导航的行为
我们声明了这样一个Action标签,这是一个 导航的行为:
<action android:id="@+id/action_page2" app:destination="@id/page2Fragment" />
app:destination的属性,声明了这个行为导航的 destination(目的地),我们可以看到,它会指印跳转到 id 为 page2Fragment 的Fragment(也就是 MainPage2Fragment)。
android:id 这个id作为Action唯一的 标识,在Fragment的某个点击事件中,我们通过id指向 对应的行为,就像这样:
btn.setOnClickListener { //点击跳转page2Fragment Navigation.findNavController(it).navigate(R.id.action_page2)}
此外,Navigation还提供了一个 app:popUpTo 属性,它的作用是声明导航行为 将 返回到 id对应的Fragment,比如,直接从Page3 返回到 Page1。
此外,Navigation 对导航行为还提供了 转场动画 的支持,它可以通过代码这样实现:
<action android:id="@+id/confirmationAction" app:destination="@id/confirmationFragment" app:enterAnim="@anim/slide_in_right" app:exitAnim="@anim/slide_out_left" app:popEnterAnim="@anim/slide_in_le