참고로, 코틀린 코드를 조금 읽기 더 좋게 만들면,
binding.aMain.navView.apply {
setOnItemSelectedListener { item ->
val action: NavDirections = when (item.itemId) {
R.id.navigation_home -> HomeFragmentDirections.actionGlobalNavigationHome()
R.id.navigation_dashboard -> DashboardFragmentDirections.actionGlobalNavigationDashboard()
R.id.navigation_mypage -> MyPageFragmentDirections.actionGlobalNavigationMypage()
else -> return true
}
navController.navigate(action)
true
}
selectedItemId = R.id.navigation_home
}
위의 코드는 맵핑 테이블을 써서 좀 더 정확하고 간결하게 변경할 수 있습니다.
enum class NavigationDrawerItemType(val naviId, val direction: NavDirections) {
HOME(R.id.navigation_home, HomeFragmentDirections.actionGlobalNavigationHome()),
DASHBOARD(R.id.navigation_dashboard, DashboardFragmentDirections.actionGlobalNavigationDashboard()),
MY_PAGE(R.id.navigation_mypage, MyPageFragmentDirections.actionGlobalNavigationMypage());
companion object {
fun from(navId: Int): NavigationDrawerItemType? {
return NavigationDrawerItemType.values().find { item -> item.navid == navId }
}
}
}
binding.aMain.navView.apply {
setOnItemSelectedListener { item ->
val action: NavDirections = NavigationDrawerItemType.from(item.itemId) ?: return true
navController.navigate(action)
true
}
selectedItemId = NavigationDrawerItemType.Home.navId
}