前言
在以往的Fragment使用中塔逃,我們都是使用Fragment的事務(wù)進(jìn)行添加,刪除料仗,替換等操作湾盗,為了快速開發(fā),我們也會(huì)自行封裝一個(gè)FragmentController立轧。在去年淹仑,Google推出了Navigation庫丙挽,目標(biāo)是更優(yōu)雅的管理Fragment。
正文
首先我們回顧一下Fragment的事務(wù):
fragmentManager.beginTransaction().add(xxx).commit()匀借;
如果是常見的多Tab切換Fragment颜阐,我們會(huì)在XML中使用FrameLayout作為Fragment的容器,然后創(chuàng)建Fragment實(shí)例吓肋,根據(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è)我們要閱讀這份代碼凳怨,坦白的說,你從這個(gè)xml可以得到的信息非常的少是鬼,你只能猜測這個(gè)頁面可能是使用了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>
從代碼量上來看,確實(shí)是增加了囤耳,但是對應(yīng)的xml中可以查看的信息增加了很多篙顺,從Activity的XML中我們把Fragment的使用區(qū)域封裝成一個(gè)Fragment,而這個(gè)Fragment綁定了一個(gè)@navigation/nav_graph文件充择,在nav_graph中描述了我們將會(huì)使用到哪些Fragment德玫。
Navigation的使用
從剛才我們的例子可以看出,Navigation的目標(biāo)是把Fragment的維護(hù)移動(dòng)到XML中椎麦,盡可能簡化Fragment的使用復(fù)雜度宰僧,提高代碼的可閱讀性和維護(hù)性。你可以把Navigation的使用看成是一個(gè)高級的Include观挎,只不過他的功能更加豐富和強(qiáng)大琴儿。
添加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兩個(gè)版本。想要使用Navigation嘁捷,必須要支持androidX造成,沒有升級到androidX的朋友真的應(yīng)該抓緊時(shí)間了。
使用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:
之前的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>
我們將會(huì)使用兩個(gè)Fragment,分別為MainFragment和SecondFragment履肃,要為他們設(shè)置好id仔沿,因?yàn)镕ragment的切換需要使用id。app:startDestination="@id/mainFragment"
必須設(shè)置尺棋,指定默認(rèn)添加的Fragment的id封锉,如果不設(shè)置會(huì)直接崩潰。
切換Fragment
從MainFragment切換到SecondFragment:
val navHostController = Navigation.findNavController(activity, R.id.nav_host_fragment)
// 跳轉(zhuǎn)到secondFragment
navHostController.navigate(R.id.secondFragment)
// 返回上一個(gè)Fragment
navHostController.navigateUp()
Navigation的更多用法
Navigation的使用就是這么簡單,如果是Fragment非常熟悉的朋友成福,大體都能猜到Navigation是怎么做到的碾局,這里就不做更多的分析了,接下來我們一起看看Navigation還提供了哪些便捷的方法奴艾。
Fragment的控制幾乎都在NavController中净当。
動(dòng)態(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的切換動(dòng)畫
實(shí)現(xiàn)Fragment的切換動(dòng)畫有兩種方法像啼,第一種非常簡單,直接在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可以自定義啟動(dòng)模式潭苞,啟動(dòng)動(dòng)畫等,id為必填項(xiàng)
app:enterAnim="@anim/enter_anim" // 進(jìn)入頁面的動(dòng)畫
app:exitAnim="@anim/exit_anim" // 退出的頁面的動(dòng)畫
app:popEnterAnim="@anim/pop_enter_anim" // 點(diǎn)擊返回或回到上一頁時(shí),上一個(gè)頁面的進(jìn)入動(dòng)畫
app:popExitAnim="@anim/pop_exit_anim" // 點(diǎn)擊返回或回到上一頁時(shí)趣倾,當(dāng)前頁面的退出動(dòng)畫
第二種士聪,通過代碼設(shè)置切換動(dòng)畫:
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
}
})
重點(diǎn)是創(chuàng)建NavOption,他包含了跳轉(zhuǎn)的各種動(dòng)畫秀菱,除了舉例的方法外振诬,還有很多其他重載的方法,這里就不做介紹了衍菱,大家可以自行查看赶么。
Fragment的切換
Fragment的切換使用NavController的navigate()方法,他重載的方法非常多脊串,在這里只介紹幾個(gè)常用的方法辫呻。
- 第一種,通過Fragment的id跳轉(zhuǎn):
navHostController.navigate(R.id.secondFragment)
請注意琼锋,這種跳轉(zhuǎn)會(huì)直接忽略你設(shè)置的Action放闺,直接顯示對應(yīng)id的Fragment。
- 第二種缕坎,通過Action的Id進(jìn)行跳轉(zhuǎn)
// 使用配置的action進(jìn)行跳轉(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進(jìn)行DeepLinkt跳轉(zhuǎn)
navHostController.navigate(Uri.parse("lzp://second/main"))
總結(jié)
Navigation上手非常的簡單匾寝,從源碼上看可以推測以后Navigation會(huì)對ViewModel提供更好的支持。Navigation更多的體驗(yàn)和用法歡迎大家留言一起討論學(xué)習(xí)荷腊。