这是我参与 8 月更文挑战的第 24 天,活动详情查看: 8月更文挑战
简介
Navigation 是一个框架,用于在 Android 应用中的“目标”之间导航,该框架提供一致的 API,无论目标是作为 Fragment、Activity 还是其他组件实现。
使用
添加依赖
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.3'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.3'
创建文件
在项目的res中创建navigation目录,同时创建navigation所需的xml文件
指定跳转
app:startDestination属性指定默认显示的页面
android:name指定当前的Fragment
android:id当前的Fragment的别名
tools:layout当前Fragment对应的布局
action在Fragment中的跳转动作
app:destination需要跳转的Fragment
app:enterAnim ,app:exitAnim设置跳转动画
app:popEnterAnim,app:popExitAnim设置栈的跳转动画 \
<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/mobile_navigation"
app:startDestination="@+id/navigation_test">
<fragment
android:id="@+id/navigation_test"
android:name="com.ihealthlabs.covidtest.ui.test.TestFragment"
android:label="@string/title_test"
tools:layout="@layout/fragment_test">
<action
android:id="@+id/action_fragment_test_to_select_otc"
app:destination="@id/fragment_test_select_otc"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@android:anim/fade_out"
app:popEnterAnim="@android:anim/fade_in"
app:popExitAnim="@anim/slide_out_right" />
</fragment>
</navigation>
在主Activity的布局中引用navigation文件
通过app:navGraph属性指定navigation文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/nav_view"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_main" />
</RelativeLayout>
跳转页面
在需要的地方通过findNavController()进行指定对应的fragment id进行跳转,示例如下
findNavController().navigate(R.id.action_fragment_test_to_select_otc)
返回页面
findNavController().navigate(R.id.action_fragment_test_to_select_otc)
通过这种方式返回UI, 当前
fragment是并没有销毁的.因为使用navigate直接指定id目标Fragment上是会创建一个新的Fragment到堆栈里的。这个时候每次navigate都会创建一个新的实例从而导致内存泄漏.
如果要在返回时销毁fragment, 可以使用findNavController().popBackStack()或者findNavController().popBackStack(R.id.action_fragment_test_to_select_otc, false)进行跳转