Navigation初探
Usage
Gradle引入
- 写的时候版本还是1.0.0-alpha1
| 1 | implementation "android.arch.navigation:navigation-fragment:$versions.navigation" | 
| 1 | implementation "android.arch.navigation:navigation-ui:$versions.navigation" | 
修改Layout文件
- 新增一个Fragment,指定道航文件的定义app:navGraph="@navigation/nav_graph"
- 指定Fragment的name android:name="androidx.navigation.fragment.NavHostFragment"固定的1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 <FrameLayout 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/container"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">
 <fragment
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/my_nav_host_fragment"
 android:name="androidx.navigation.fragment.NavHostFragment"
 app:navGraph="@navigation/nav_graph"
 app:defaultNavHost="true"
 />
 </FrameLayout>
新建刚才指定的naviGraph文件
- 在res目录下新建一个navigation文件夹,新建一个navi_graph.xml文件
- 根节点navigation,指定初始的fragmentapp:startDestination="@+id/launcher_home"
- 子节点fragment定义页面,id就是导航的页面标的,name是Fragment的全路径
- action是- fragment的子节点,定义了跳转的动作,通过action的- id来寻找页面并导航到id标定的fragment,
| 1 | 
 | 
最后在代码中进行导航
- 通过Navigation.findNavController方法找到导航控制器,navigate对应的action的id就会导航到对应的Fragment
| 1 | class MainFragment : Fragment() { |