什么是 Android Navigation?
Android Navigation 是 Jetpack 的一部分,旨在简化应用内不同界面(如 Fragment 或 Activity)之间的导航。 它通过声明式的导航图(Navigation Graph)统一管理跳转逻辑,减少样板代码,并支持深层链接、返回栈管理等高级功能。
核心概念
- NavHost:承载导航目标的容器,通常为
NavHostFragment。 - Navigation Graph:XML 文件,定义所有可导航的目标及其关系。
- Destination:导航目标,通常是 Fragment 或 Activity。
- Action:从一个 Destination 到另一个的跳转行为。
基本使用示例
在 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"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.HomeFragment"
android:label="Home" >
<action
android:id="@+id/action_home_to_detail"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/detailFragment"
android:name="com.example.DetailFragment"
android:label="Detail" />
</navigation>
在 Activity 布局中嵌入 NavHostFragment:
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="@navigation/nav_graph"
app:defaultNavHost="true" />
优势
- 可视化导航结构(可通过 Android Studio 的 Navigation Editor 编辑)
- 自动处理返回栈和过渡动画
- 类型安全的参数传递(配合 Safe Args 插件)
- 支持深层链接(Deep Link)和动态功能模块导航
参考资料
更多信息请访问官方文档: Android Navigation 官方指南