新一代的Fragment管理庫:Navigation

前言

在以往的Fragment使用中,我們都是使用Fragment的事務進行添加,刪除,替換等操作,爲了快速開發,我們也會自行封裝一個FragmentController。在去年,Google推出了Navigation庫,目標是更優雅的管理Fragment。

正文

首先我們回顧一下Fragment的事務:

fragmentManager.beginTransaction().add(xxx).commit();

如果是常見的多Tab切換Fragment,我們會在XML中使用FrameLayout作爲Fragment的容器,然後創建Fragment實例,根據不同情況放入FrameLayout中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

假設我們要閱讀這份代碼,坦白的說,你從這個xml可以得到的信息非常的少,你只能猜測這個頁面可能是使用了Fragment僅此而已,然後再去找Java或Kotlin文件,具體查看FrameLayout都使用了哪些功能邏輯。

Navigation

現在我們用Navigation庫,完成剛纔的多Tab切換邏輯:

MainActivity的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"
    tools:context=".MainActivity">

    <!-- fragment的集合 -->
    <fragment
        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>
nav_graph文件:

<?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/mainFragment"> <!-- 開始的fragment -->

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.lzp.navigation.fragment.MainFragment"
        android:label="main"
        tools:layout="@layout/fragment_main" />

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.lzp.navigation.fragment.SecondFragment"
        android:label="second"
        tools:layout="@layout/fragment_sec" />

</navigation>

從代碼量上來看,確實是增加了,但是對應的xml中可以查看的信息增加了很多,從Activity的XML中我們把Fragment的使用區域封裝成一個Fragment,而這個Fragment綁定了一個@navigation/nav_graph文件,在nav_graph中描述了我們將會使用到哪些Fragment。

Navigation的使用

從剛纔我們的例子可以看出,Navigation的目標是把Fragment的維護移動到XML中,儘可能簡化Fragment的使用複雜度,提高代碼的可閱讀性和維護性。你可以把Navigation的使用看成是一個高級的Include,只不過他的功能更加豐富和強大。

添加Gradle依賴

 dependencies {
      def nav_version = "2.1.0"

      // Java
      implementation "androidx.navigation:navigation-fragment:$nav_version"
      implementation "androidx.navigation:navigation-ui:$nav_version"

      // Kotlin
      implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
      implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

    }

Google提供了Java和Kotlin兩個版本。想要使用Navigation,必須要支持androidX,沒有升級到androidX的朋友真的應該抓緊時間了。

使用NavHostFragment

<!-- fragment的集合 -->
    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

把FrameLayout容器替換成NavHostFragment,app:navGraph="@navigation/nav_graph"是綁定對應的佈局文件。@navigation只有在android studio 3.3以上版本才支持。

創建navGraph

在res文件加下創建navigation文件夾,在該文件夾下創建你需要的xml:

之前的Demo的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/mainFragment"> <!-- 開始的fragment -->

    <fragment
        android:id="@+id/mainFragment"
        android:name="com.lzp.navigation.fragment.MainFragment"
        android:label="main"
        tools:layout="@layout/fragment_main" />

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.lzp.navigation.fragment.SecondFragment"
        android:label="second"
        tools:layout="@layout/fragment_sec" />

</navigation>

我們將會使用兩個Fragment,分別爲MainFragment和SecondFragment,要爲他們設置好id,因爲Fragment的切換需要使用id。app:startDestination="@id/mainFragment"必須設置,指定默認添加的Fragment的id,如果不設置會直接崩潰。

切換Fragment

從MainFragment切換到SecondFragment:

val navHostController = Navigation.findNavController(activity, R.id.nav_host_fragment)
// 跳轉到secondFragment
navHostController.navigate(R.id.secondFragment)
// 返回上一個Fragment
navHostController.navigateUp()

Navigation的更多用法

Navigation的使用就是這麼簡單,如果是Fragment非常熟悉的朋友,大體都能猜到Navigation是怎麼做到的,這裏就不做更多的分析了,接下來我們一起看看Navigation還提供了哪些便捷的方法。

Fragment的控制幾乎都在NavController中。

動態設置NavGraph

val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
// 與inflater類似,加載xml文件
val navGraph = navController.navInflater.inflate(R.navigation.nav_graph)
// 設置NavGraph,還有其他重載方法
navController.setGraph(navGraph, Bundle())

Fragment的切換動畫

實現Fragment的切換動畫有兩種方法,第一種非常簡單,直接在XML中寫:

<fragment
        android:id="@+id/mainFragment"
        android:name="com.lzp.navigation.fragment.MainFragment"
        android:label="main"
        tools:layout="@layout/fragment_main">

        <action
            android:id="@+id/to_second"
            app:destination="@id/secondFragment"
            app:enterAnim="@anim/enter_anim"
            app:exitAnim="@anim/exit_anim"
            app:popEnterAnim="@anim/pop_enter_anim"
            app:popExitAnim="@anim/pop_exit_anim" />

    </fragment>

action可以自定義啓動模式,啓動動畫等,id爲必填項
app:enterAnim="@anim/enter_anim" // 進入頁面的動畫
app:exitAnim="@anim/exit_anim" // 退出的頁面的動畫
app:popEnterAnim="@anim/pop_enter_anim" // 點擊返回或回到上一頁時,上一個頁面的進入動畫
app:popExitAnim="@anim/pop_exit_anim" // 點擊返回或回到上一頁時,當前頁面的退出動畫

第二種,通過代碼設置切換動畫:

 navHostController.navigate(R.id.to_second, bundle, navOptions {
                anim {
                    enter = R.anim.enter_anim
                    exit = R.anim.exit_anim
                    popEnter = R.anim.pop_enter_anim
                    popExit = R.anim.pop_exit_anim
                }
})

重點是創建NavOption,他包含了跳轉的各種動畫,除了舉例的方法外,還有很多其他重載的方法,這裏就不做介紹了,大家可以自行查看。

Fragment的切換

Fragment的切換使用NavController的navigate()方法,他重載的方法非常多,在這裏只介紹幾個常用的方法。

  • 第一種,通過Fragment的id跳轉:
navHostController.navigate(R.id.secondFragment)

請注意,這種跳轉會直接忽略你設置的Action,直接顯示對應id的Fragment。

  • 第二種,通過Action的Id進行跳轉
// 使用配置的action進行跳轉
navHostController.navigate(R.id.to_second)

第三種,自定義NavDirections

// 自定義NavDirections
            navHostController.navigate(object : NavDirections {

                override fun getArguments(): Bundle = bundle

                override fun getActionId(): Int = R.id.to_second

 })

前兩中也都有Bundle參數的跳轉方法,在arguments中得到傳遞的參數。

監聽Fragment切換

private val onDestinationChangedListener =
        NavController.OnDestinationChangedListener { _, destination, _ -> Log.e("lzp", destination.label.toString()) }
 val navHostController = Navigation.findNavController(this, R.id.nav_host_fragment)       
 // 設置監聽
 navHostController.addOnDestinationChangedListener(onDestinationChangedListener)
 // 移除監聽
 navHostController.removeOnDestinationChangedListener(onDestinationChangedListener)

DeepLink

可以通過配置Uri的形式跳轉:

<?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/mainFragment"> <!-- 開始的fragment -->
	
	...

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.lzp.navigation.fragment.SecondFragment"
        android:label="second"
        tools:layout="@layout/fragment_sec">

        <deepLink app:uri="lzp://main/second" />

    </fragment>

    <activity
        android:id="@+id/to_second_activity"
        android:name="com.lzp.navigation.SecondActivity">

        <deepLink app:uri="lzp://second/main" />

    </activity>

</navigation>

// 使用Uri進行DeepLinkt跳轉
navHostController.navigate(Uri.parse("lzp://second/main"))

總結

Navigation上手非常的簡單,從源碼上看可以推測以後Navigation會對ViewModel提供更好的支持。Navigation更多的體驗和用法歡迎大家留言一起討論學習。

發佈了116 篇原創文章 · 獲贊 59 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章