Compose Navigation
HomeScreen -> Profile -> Settings -> ๋ค๋ก๊ฐ๊ธฐ -> HomeScreen -> ๋ค๋ก๊ฐ๊ธฐ -> ์ฑ์ข ๋ฃ
Build.Gradle ์ถ๊ฐ
dependencies {
def nav_version = "2.4.2"
// Navigation
implementation "androidx.navigation:navigation-compose:$nav_version"
}
sealed class BottomBarScreen(
val route: String,
val title: String,
val icon: ImageVector
){
object Home: BottomBarScreen(
route = "Home",
title = "Home",
icon = Icons.Default.Home
)
object Profile: BottomBarScreen(
route = "Profile",
title = "Profile",
icon = Icons.Default.Person
)
object Settings: BottomBarScreen(
route = "Settings",
title = "Settings",
icon = Icons.Default.Settings
)
}
@Composable
fun BottomNavGraph(navController: NavHostController) {
NavHost(
navController = navController,
startDestination = BottomBarScreen.Home.route
) {
composable(route = BottomBarScreen.Home.route){
HomeScreen()
}
composable(route = BottomBarScreen.Profile.route){
ProfileScreen()
}
composable(route = BottomBarScreen.Settings.route){
SettingScreen()
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Samplenavigation2Theme {
// A surface container using the 'background' color from the theme
MainScreen()
}
}
}
}
@Composable
fun BottomBar(navController: NavHostController) {
val screens = listOf(
BottomBarScreen.Home,
BottomBarScreen.Profile,
BottomBarScreen.Settings
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
BottomNavigation {
screens.forEach { screens ->
AddItem(screen = screens, currentDestination = currentDestination, navController =navController )
}
}
}
@Composable
fun RowScope.AddItem(
screen: BottomBarScreen,
currentDestination: NavDestination?,
navController: NavHostController
) {
BottomNavigationItem(
label = {
Text(text = screen.title)
},
icon = {
Icon(imageVector = screen.icon, contentDescription = "Navigation Icon")
},
selected = currentDestination?.hierarchy?.any {
it.route == screen.route
} == true,
unselectedContentColor = LocalContentColor.current.copy(alpha = ContentAlpha.disabled),
onClick = {
navController.navigate(screen.route){
popUpTo(navController.graph.findStartDestination().id)
launchSingleTop =true
}
}
)
}
@Composable
fun MainScreen() {
val navController = rememberNavController()
Scaffold(
bottomBar = { BottomBar(navController = navController)}
) {
BottomNavGraph(navController = navController)
}
}
GitHub : ์ฝ๋ ์๋ฃ