新一代的Fragment管理庫:Navigation

前言

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

安遠網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián)公司,安遠網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為安遠1000+提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請找那個售后服務(wù)好的安遠做網(wǎng)站的公司定做!

正文

首先我們回顧一下Fragment的事務(wù):

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

如果是常見的多Tab切換Fragment,我們會在XML中使用FrameLayout作為Fragment的容器,然后創(chuàng)建Fragment實例,根據(jù)不同情況放入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>

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

Navigation

現(xiàn)在我們用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>

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

Navigation的使用

從剛才我們的例子可以看出,Navigation的目標是把Fragment的維護移動到XML中,盡可能簡化Fragment的使用復(fù)雜度,提高代碼的可閱讀性和維護性。你可以把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的朋友真的應(yīng)該抓緊時間了。

使用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"是綁定對應(yīng)的布局文件。@navigation只有在android studio 3.3以上版本才支持。

創(chuàng)建navGraph

在res文件加下創(chuàng)建navigation文件夾,在該文件夾下創(chuàng)建你需要的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,要為他們設(shè)置好id,因為Fragment的切換需要使用id。app:startDestination="@id/mainFragment"必須設(shè)置,指定默認添加的Fragment的id,如果不設(shè)置會直接崩潰。

切換Fragment

從MainFragment切換到SecondFragment:

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

Navigation的更多用法

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

Fragment的控制幾乎都在NavController中。

動態(tài)設(shè)置NavGraph

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

Fragment的切換動畫

實現(xiàn)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" // 點擊返回或回到上一頁時,當前頁面的退出動畫

第二種,通過代碼設(shè)置切換動畫:

 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
                }
})

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

Fragment的切換

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

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

請注意,這種跳轉(zhuǎn)會直接忽略你設(shè)置的Action,直接顯示對應(yīng)id的Fragment。

  • 第二種,通過Action的Id進行跳轉(zhuǎn)
// 使用配置的action進行跳轉(zhuǎn)
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參數(shù)的跳轉(zhuǎn)方法,在arguments中得到傳遞的參數(shù)。

監(jiān)聽Fragment切換

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

DeepLink

可以通過配置Uri的形式跳轉(zhuǎn):

<?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跳轉(zhuǎn)
navHostController.navigate(Uri.parse("lzp://second/main"))

總結(jié)

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

網(wǎng)站名稱:新一代的Fragment管理庫:Navigation
網(wǎng)站網(wǎng)址:http://muchs.cn/article10/gesego.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、品牌網(wǎng)站設(shè)計、建站公司移動網(wǎng)站建設(shè)、手機網(wǎng)站建設(shè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)