계속 회사일로 바뻐서 작업을 못하다가.. 이대로 가면 아무것도 못할거 같아서 앱작업을 좀 해보려고 한다.
Compose를 사용해서 앱을 만들텐데, 우선 bottom navigation을 사용해보자
우선 종속성을 추가하자.
여기에서 최신버전을 확인하면 된다.
dependencies {
implementation("androidx.navigation:navigation-compose:$nav_version")
}
2022/11/16일 현재 최신버전은 2.5.3이다.
기본적으로 옮겨질 화면이 있어여 하므로,
사용할 화면 5개를 미리 만들어 보았다.
@Composable
fun AccountBookView() {
Text(text = "여기는 가계부")
}
@Composable
fun CalculateView() {
Text(text = "여기는 Calculte")
}
@Composable
fun HomeView() {
Text(text = "여기는 홈")
}
@Composable
fun SettingView() {
Text(text = "여기는 세팅")
}
@Composable
fun SimulatorView() {
Text(text = "여기는 시뮬레이터")
}
이동을 위한 정보를 담고있는 class를 만듭니다.
selad Class에 대한 정보는 여기서 참고할수있습니다.
sealed class BottomNavItem(
val screenRoute: String
) {
object Calculate : BottomNavItem(Const.CALCULATE)
object AccountBook : BottomNavItem(Const.ACCOUNT_BOOK)
object Home :BottomNavItem(Const.HOME)
object Simulator : BottomNavItem(Const.SIMULATOR)
object Settings : BottomNavItem(Const.SETTING)
}
Const 파일에 값을 String으로 만들어 넣어뒀습니다.
이동관련 NavHost 함수를 만듭니다.
이 함수는 화면과 Item을 연결해주는 연결다리입니다.
@Composable
fun NavGraph(navController: NavHostController) {
NavHost(navController = navController, startDestination = BottomNavItem.Home.screenRoute) {
composable(BottomNavItem.Calculate.screenRoute) {
CalculateView()
}
composable (BottomNavItem.AccountBook.screenRoute) {
AccountBookView()
}
composable (BottomNavItem.Home.screenRoute) {
HomeView()
}
composable (BottomNavItem.Simulator.screenRoute) {
SimulatorView()
}
composable (BottomNavItem.Settings.screenRoute) {
SettingView()
}
}
}
실제 하단에 들어갈 바텀바를 만들면 됩니당
@Composable
fun BottomNavigationBar(navController: NavController) {
val items = listOf(
BottomNavItem.Calculate,
BottomNavItem.AccountBook,
BottomNavItem.Home,
BottomNavItem.Simulator,
BottomNavItem.Settings
)
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
icon = { Icon(painterResource(id = R.drawable.ic_launcher_foreground),null) },
label = { Text(text = item.screenRoute) },
selected = currentRoute == item.screenRoute,
onClick = { navController.navigate(item.screenRoute) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
)
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyTheme {
// A surface container using the 'background' color from the theme
val navController = rememberNavController()
Scaffold(
bottomBar = { BottomNavigationBar(navController = navController) }
) {
Box(Modifier.padding(it)){
NavGraph(navController = navController)
}
}
}
}
}
}
해당 과정에서 BottomNavItem에 icon정보를 담아두면 편하게 작업할수있습니다.
위와 같이 적용하면 정상적으로 bottom Navigation을 이용할수 있습니다.