通過查看源碼發(fā)現(xiàn),在導航視圖文件中為fragment添加的name屬性可以通過FragmentNavigator.Destination的getClassName()脏嚷,而NavController也提供了得到當前Destination的方法getCurrentDestination()赁炎,于是就可以在activity中判斷出當前顯示的是哪個Fragment。
Talk is cheap. Show me the code.
override fun onBackPressed() {
val navController = findNavController(this, cn.hisw.sjtw.R.id.nav_host_fragment)
val currentDestination = navController.currentDestination // 得到當前目的地
if (currentDestination is FragmentNavigator.Destination){ //對Destination進行強制轉(zhuǎn)換
when (currentDestination.className){
//如果當前頁是SplashFragment或StartFragment或MainFragment則直接退出Activity
SplashFragment::class.java.name ,
StartFragment::class.java.name ,
MainFragment::class.java.name ->
finish()
else -> super.onBackPressed()
}
}else {
super.onBackPressed()
}
}