data class NavigationItem(
val title: String,
val selectedIcon: ImageVector,
val unselectedIcon: ImageVector,
val route: String
)
@OptIn(ExperimentalMaterial3Api::class)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
DrawerM3Theme {
NavHost(
navController = navController,
startDestination = "home"
) {
composable("home") {
HomeScreen()
}
composable("add") {
AddScreen()
}
composable("account") {
AccountScreen()
}
}
val items = listOf(
NavigationItem(
title = "Home",
selectedIcon = Icons.Filled.Home,
unselectedIcon = Icons.Outlined.Home,
route = "home"
),
NavigationItem(
title = "Add",
selectedIcon = Icons.Filled.Add,
unselectedIcon = Icons.Outlined.Add,
route = "add"
),
NavigationItem(
title = "Account",
selectedIcon = Icons.Filled.AccountBox,
unselectedIcon = Icons.Outlined.AccountBox,
route = "account"
)
)
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
var selectedItemIndex by rememberSaveable {
mutableStateOf(0)
}
ModalNavigationDrawer(
drawerContent = {
ModalDrawerSheet {
Spacer(modifier = Modifier.height(16.dp))
items.forEachIndexed { index, item ->
NavigationDrawerItem(
label = { Text(text = item.title) },
selected = index == selectedItemIndex,
onClick = {
navController.navigate(item.route)
selectedItemIndex = index
scope.launch {
drawerState.close()
}
},
icon = {
Icon(
imageVector = if (index == selectedItemIndex) {
item.selectedIcon
} else item.unselectedIcon,
contentDescription = item.title
)
},
modifier = Modifier
.padding(NavigationDrawerItemDefaults.ItemPadding)
)
}
}
},
drawerState = drawerState,
) {
Scaffold(
topBar = {
TopAppBar(title = {
Text(text = "Home")
},
navigationIcon = {
IconButton(onClick = {
scope.launch {
drawerState.open()
}
}) {
Icon(
imageVector = Icons.Default.Menu,
contentDescription = "Menu"
)
}
},
actions = {
IconButton(onClick = { }) {
Icon(
imageVector = Icons.Default.Settings,
contentDescription = "Settings"
)
}
}
)
}
) {
}
}
}
}
}
}
}
@Composable
fun HomeScreen() {
Box(modifier = Modifier.fillMaxSize()) {
Text(
text = "Home",
color = MaterialTheme.colorScheme.error,
)
}
}
@Composable
fun AddScreen() {
Box(modifier = Modifier.fillMaxSize()) {
Text(
text = "Add",
color = MaterialTheme.colorScheme.primary
)
}
}
@Composable
fun AccountScreen() {
Box(modifier = Modifier.fillMaxSize()) {
Text(
text = "Account",
color = MaterialTheme.colorScheme.surface
)
}
}