天天看點

新一代的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:

新一代的Fragment管理庫:Navigation前言正文總結

之前的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

 })           

監聽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

<?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"))           

總結