从官方整了个demo下来,全部kotlin编写,对我这种基本从未用过kotlin的老年选手来说理解真是难搞。
MainActivity
首先按照官方步骤,从MainActivity里走起。
先看布局。一眼就能看到这玩意。
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/mobile_navigation"
app:defaultNavHost="true"
/>
android:name=“androidx.navigation.fragment.NavHostFragment” and app:defaultNavHost=“true” connect the system back button to the NavHostFragment
app:navGraph="@navigation/mobile_navigation" associates the NavHostFragment with a navigation graph. This navigation graph specifies all the destinations the user can navigate to, in this NavHostFragment.
官方说明: app:defaultNavHost=true和name=NavHostFragment将返回键接给了NavHostFragment,意思应该就是这样设置之后返回键可以用于fragment回退切换而不是bang掉了activity。
下一句也没什么好说的,连上了一个graph。graph是这套逻辑的核心。
然后进代码块。官方这个demo从界面上看就知道很简单,只包含几个点击事件的处理,所以关注的逻辑基本只有点击事件就够了。
Finally, when a user does something like clicking a button, you need to trigger a navigate command. A special class called the NavController is what triggers the fragment swaps in the NavHostFragment.
来看看官方关于点击事件的说明。
当用户执行诸如单击按钮之类的操作时,需要触发导航命令。一个名为NavController的特殊类触发了NavHostFragment中的片段交换。
val host: NavHostFragment = supportFragmentManager
.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return
// Set up Action Bar
val navController = host.navController
navController.addOnNavigatedListener {
_, destination ->
val dest: String = try {
resources.getResourceName(destination.id)
} catch (e: Resources.NotFoundException) {
Integer.toString(destination.id)
}
Toast.makeText(this@MainActivity, "Navigated to $dest",
Toast.LENGTH_SHORT).show()