Material3 ‐ NavigationDrawer - devrath/Material-3-Design-Kit GitHub Wiki
Contents |
---|
Demo representation |
Code |
Light Theme |
Dark Theme |
---|---|
![]() |
![]() |
data class NavigationData(
val title: String,
val selectedIcon: ImageVector,
val unSelectedIcon: ImageVector
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NavigationContent() {
val cxt = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val items = listOf(
NavigationData(
title = "Home",
selectedIcon = Icons.Filled.Home,
unSelectedIcon = Icons.Outlined.Home
),
NavigationData(
title = "Profile",
selectedIcon = Icons.Filled.Android,
unSelectedIcon = Icons.Outlined.Android
),
NavigationData(
title = "Settings",
selectedIcon = Icons.Filled.Settings,
unSelectedIcon = Icons.Outlined.Settings
)
)
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
var selectedItemIndex by rememberSaveable { mutableIntStateOf(0) }
ModalNavigationDrawer(
drawerContent = {
// Items of the drawer
ModalDrawerSheet {
Spacer(modifier = Modifier.height(16.dp))
items.forEachIndexed { index, navigationData ->
NavigationDrawerItem(
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
label = {
Text(text = navigationData.title)
},
// Highlighting the item when it is selected
selected = index == selectedItemIndex,
onClick = {
selectedItemIndex = index
coroutineScope.launch {
drawerState.close()
}
},
icon = {
Icon(
imageVector = if (selectedItemIndex == index) {
navigationData.selectedIcon
} else {
navigationData.unSelectedIcon
}, contentDescription = navigationData.title
)
}
)
}
}
},
drawerState = drawerState
) {
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopAppBar(title = {
Text(text = "Drawer Demo")
},
navigationIcon = {
IconButton(
onClick = {
coroutineScope.launch {
drawerState.open()
}
}
) {
Icon(
imageVector = Icons.Default.Menu,
contentDescription = "Menu"
)
}
}
)
}
) {
Box(
modifier = Modifier.padding(it)
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = items[selectedItemIndex].title,
fontSize = 26.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
}