Drawer 是 Jetpack Compose 中用來顯示側邊滑出的導航畫面的元件,通常用於提供 App 中的導航選項或其他輔助操作。當使用者從螢幕邊緣滑動或點擊某個按鈕時,Drawer 會從螢幕邊緣滑出,顯示相關的內容。
rememberDrawerState
:創建一個 DrawerState,來控制 Drawer 的開啟或關閉。rememberCoroutineScope
:由於 drawerState.open() 為suspend 方法,因此要使用此來處理 open、close 。ModalNavigationDrawer
:滑出的導覽畫面
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DrawerComposable(modifier: Modifier = Modifier) {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
ModalNavigationDrawer(
drawerContent = {
ModalDrawerSheet {
Text("Drawer title", modifier = Modifier.padding(16.dp))
NavigationDrawerItem(
label = { Text(text = "Item 1") },
selected = false,
onClick = { }
)
NavigationDrawerItem(
icon = {
Icon(
imageVector = Icons.Default.Call,
contentDescription = "Call"
)
},
label = { Text(text = "Item 2") },
selected = false,
onClick = {
scope.launch {
drawerState.close()
}
}
)
NavigationDrawerItem(
label = { Text(text = "Item 3") },
selected = false,
onClick = { }
)
}
},
drawerState = drawerState
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(text = "Navigation Drawer Example")
},
navigationIcon = {
IconButton(onClick = {
scope.launch {
drawerState.apply {
if (isClosed) drawerState.open() else drawerState.close()
}
}
}) {
Icon( //Show Menu Icon on TopBar
imageVector = Icons.Default.Menu,
contentDescription = "Menu"
)
}
}
)
}
) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
modifier = Modifier.padding(8.dp),
text = "Drawer Example"
)
}
}
}
}
題外話:
這邊特別感謝朋友提醒中英文之間要空格會比較好閱讀。
共勉之: 中文文案排版指北