Trình đơn thả xuống cho phép người dùng nhấp vào một biểu tượng, trường văn bản hoặc thành phần khác, sau đó chọn trong danh sách các lựa chọn trên một giao diện tạm thời. Hướng dẫn này mô tả cách tạo cả trình đơn cơ bản và trình đơn phức tạp hơn có dấu phân tách và biểu tượng.
Nền tảng API
Sử dụng các thành phần DropdownMenu, DropdownMenuItem, IconButton và ExposedDropdownMenuBox để triển khai trình đơn thả xuống. Các thành phần DropdownMenu và DropdownMenuItem được dùng để hiển thị các mục trong trình đơn, còn IconButton hoặc các thành phần khác có thể kích hoạt việc hiển thị trình đơn.
ExposedDropdownMenuBox được dùng để tạo trình đơn đính kèm vào trường văn bản.
Các tham số chính cho thành phần DropdownMenu bao gồm:
expanded: Cho biết trình đơn có hiển thị hay không.onDismissRequest: Dùng để xử lý việc đóng trình đơn.content: Nội dung có thể kết hợp của trình đơn, thường chứa các thành phần kết hợpDropdownMenuItem.
Các tham số chính cho DropdownMenuItem bao gồm:
text: Xác định nội dung hiển thị trong mục trình đơn.onClick: Lệnh gọi lại để xử lý hoạt động tương tác với mục trong trình đơn.
Tạo trình đơn thả xuống cơ bản
Đoạn mã sau đây minh hoạ cách triển khai DropdownMenu tối thiểu:
@Composable fun MinimalDropdownMenu() { var expanded by remember { mutableStateOf(false) } Box( modifier = Modifier .padding(16.dp) ) { IconButton(onClick = { expanded = !expanded }) { Icon(painter = rememberVectorPainter(AppIcons.MoreVert), contentDescription = "More options") } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { DropdownMenuItem( text = { Text("Option 1") }, onClick = { /* Do something... */ } ) DropdownMenuItem( text = { Text("Option 2") }, onClick = { /* Do something... */ } ) } } }
Các điểm chính về mã
- Xác định một
DropdownMenucơ bản chứa hai mục trong trình đơn. - Tham số
expandedkiểm soát chế độ hiển thị của trình đơn ở trạng thái mở rộng hoặc thu gọn. - Tham số
onDismissRequestxác định một lệnh gọi lại thực thi khi người dùng đóng trình đơn. - Thành phần kết hợp
DropdownMenuItemđại diện cho các mục có thể chọn trong trình đơn thả xuống. IconButtonkích hoạt thao tác mở rộng và thu gọn trình đơn.
Kết quả
Tạo trình đơn thả xuống dài hơn
DropdownMenu có thể cuộn theo mặc định nếu không thể hiển thị tất cả các mục trong trình đơn cùng một lúc. Đoạn mã sau đây tạo một trình đơn thả xuống dài hơn, có thể cuộn:
@Composable fun LongBasicDropdownMenu() { var expanded by remember { mutableStateOf(false) } // Placeholder list of 100 strings for demonstration val menuItemData = List(100) { "Option ${it + 1}" } Box( modifier = Modifier .padding(16.dp) ) { IconButton(onClick = { expanded = !expanded }) { Icon(painter = rememberVectorPainter(AppIcons.MoreVert), contentDescription = "More options") } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { menuItemData.forEach { option -> DropdownMenuItem( text = { Text(option) }, onClick = { /* Do something... */ } ) } } } }
Các điểm chính về mã
DropdownMenucó thể cuộn được khi tổng chiều cao của nội dung vượt quá không gian có sẵn. Mã này tạo mộtDropdownMenucó thể cuộn, hiển thị 100 mục phần giữ chỗ.- Vòng lặp
forEachtạo động các thành phần kết hợpDropdownMenuItem. Các mục không được tạo từng phần, nghĩa là tất cả 100 mục thả xuống đều được tạo và tồn tại trong thành phần. IconButtonkích hoạt việc mở rộng và thu gọnDropdownMenukhi được nhấp vào.- Hàm lambda
onClicktrong mỗiDropdownMenuItemcho phép bạn xác định hành động được thực hiện khi người dùng chọn một mục trong trình đơn.
Kết quả
Đoạn mã trước đó tạo ra trình đơn có thể cuộn sau:
Tạo trình đơn thả xuống dài hơn có đường phân chia
Đoạn mã sau đây cho thấy cách triển khai nâng cao hơn của trình đơn thả xuống. Trong đoạn mã này, các biểu tượng ở đầu và cuối được thêm vào các mục trong trình đơn, đồng thời các đường phân chia sẽ phân tách các nhóm mục trong trình đơn.
@Composable fun DropdownMenuWithDetails() { var expanded by remember { mutableStateOf(false) } Box( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { IconButton(onClick = { expanded = !expanded }) { Icon(painter = rememberVectorPainter(AppIcons.MoreVert), contentDescription = "More options") } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { // First section DropdownMenuItem( text = { Text("Profile") }, leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.Person), contentDescription = null) }, onClick = { /* Do something... */ } ) DropdownMenuItem( text = { Text("Settings") }, leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.Settings), contentDescription = null) }, onClick = { /* Do something... */ } ) HorizontalDivider() // Second section DropdownMenuItem( text = { Text("Send Feedback") }, leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.Feedback), contentDescription = null) }, trailingIcon = { Icon(painter = rememberVectorPainter(AppIcons.Send), contentDescription = null) }, onClick = { /* Do something... */ } ) HorizontalDivider() // Third section DropdownMenuItem( text = { Text("About") }, leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.Info), contentDescription = null) }, onClick = { /* Do something... */ } ) DropdownMenuItem( text = { Text("Help") }, leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.Help), contentDescription = null) }, trailingIcon = { Icon(painter = rememberVectorPainter(AppIcons.OpenInNew), contentDescription = null) }, onClick = { /* Do something... */ } ) } } }
Mã này xác định một DropdownMenu trong Box.
Các điểm chính về mã
- Tham số
leadingIconvàtrailingIconthêm biểu tượng vào đầu và cuốiDropdownMenuItem. IconButtonkích hoạt việc mở rộng trình đơn.DropdownMenuchứa một số thành phần kết hợpDropdownMenuItem, mỗi thành phần đại diện cho một hành động có thể chọn.- Thành phần kết hợp
HorizontalDividerchèn một đường ngang để phân tách các nhóm mục trong trình đơn.
Kết quả
Đoạn mã trước tạo ra một trình đơn thả xuống có biểu tượng và đường phân chia:
Bản cập nhật M3 Expressive
Material 3 Expressive giới thiệu DropdownMenuPopup, DropdownMenuGroup và CheckableDropdownMenuItem dưới dạng các tuỳ chọn bổ sung bên cạnh DropdownMenu và DropdownMenuItem để tạo trình đơn được phân đoạn với các mục được nhóm, khoảng trống và trạng thái có thể kiểm tra.
Để biết thêm thông tin về các bản cập nhật M3 Expressive cho trình đơn, hãy xem nguyên tắc về trình đơn Material Design 3.
Trình đơn được phân đoạn
Trình đơn được phân đoạn nhóm các hành động có liên quan thành các phần hình ảnh riêng biệt được phân tách bằng khoảng trống hoặc đường phân chia. Đoạn mã sau đây minh hoạ cách triển khai trình đơn thả xuống được phân đoạn bằng DropdownMenuPopup, DropdownMenuGroup và CheckableDropdownMenuItem:
@OptIn(ExperimentalMaterial3Api::class) @Composable fun GroupedMenuSample() { val groupInteractionSource = remember { MutableInteractionSource() } var expanded by remember { mutableStateOf(false) } val groupLabels = listOf("Modification", "Navigation") val groupItemLabels = listOf(listOf("Edit", "Settings"), listOf("Home", "More Options")) val groupItemLeadingIcons = listOf(listOf(AppIcons.Edit, AppIcons.Settings), listOf(null, AppIcons.Info)) val groupItemCheckedLeadingIcons = listOf( listOf(AppIcons.EditFilled, AppIcons.SettingsFilled), listOf(AppIcons.Check, AppIcons.InfoFilled), ) val groupItemTrailingIcons: List<List<ImageVector?>> = listOf(listOf(null, null), listOf(AppIcons.Home, AppIcons.MoreVert)) val groupItemCheckedTrailingIcons: List<List<ImageVector?>> = listOf(listOf(null, null), listOf(AppIcons.HomeFilled, AppIcons.MoreVert)) val groupItemSupportingText: List<List<String?>> = listOf(listOf("Edit mode", null), listOf(null, "Opens menu")) val checked = remember { listOf(mutableStateListOf(false, false), mutableStateListOf(false, false)) } Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) { // Icon button should have a tooltip associated with it for a11y. TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Above), tooltip = { PlainTooltip { Text("Localized description") } }, state = rememberTooltipState(), ) { IconButton(onClick = { expanded = true }) { Icon(painter = rememberVectorPainter(AppIcons.MoreVert), contentDescription = "Localized description") } } DropdownMenuPopup(expanded = expanded, onDismissRequest = { expanded = false }) { val groupCount = groupLabels.size groupLabels.fastForEachIndexed { groupIndex, label -> DropdownMenuGroup( shapes = MenuDefaults.groupShape(groupIndex, groupCount), interactionSource = groupInteractionSource, ) { MenuDefaults.DropdownMenuGroupLabel { Text(label) } HorizontalDivider(modifier = Modifier.padding(MenuDefaults.HorizontalDividerPadding)) val groupItemCount = groupItemLabels[groupIndex].size groupItemLabels[groupIndex].fastForEachIndexed { itemIndex, itemLabel -> CheckableDropdownMenuItem( text = { Text(itemLabel) }, supportingText = groupItemSupportingText[groupIndex][itemIndex]?.let { supportingText -> { Text(supportingText) } }, shapes = MenuDefaults.itemShape(itemIndex, groupItemCount), leadingIcon = groupItemLeadingIcons[groupIndex][itemIndex]?.let { iconData -> { Icon( painter = rememberVectorPainter(iconData), modifier = Modifier.size(MenuDefaults.LeadingIconSize), contentDescription = null, ) } }, checkedLeadingIcon = { Icon( painter = rememberVectorPainter(groupItemCheckedLeadingIcons[groupIndex][itemIndex]), modifier = Modifier.size(MenuDefaults.LeadingIconSize), contentDescription = null, ) }, trailingContent = if (checked[groupIndex][itemIndex]) { groupItemCheckedTrailingIcons[groupIndex][itemIndex]?.let { iconData -> { Icon( painter = rememberVectorPainter(iconData), modifier = Modifier.size(MenuDefaults.TrailingIconSize), contentDescription = null, ) } } } else { groupItemTrailingIcons[groupIndex][itemIndex]?.let { iconData -> { Icon( painter = rememberVectorPainter(iconData), modifier = Modifier.size(MenuDefaults.TrailingIconSize), contentDescription = null, ) } } }, checked = checked[groupIndex][itemIndex], onCheckedChange = { checked[groupIndex][itemIndex] = it }, ) } } if (groupIndex != groupCount - 1) { Spacer(Modifier.height(MenuDefaults.GroupSpacing)) } } if (checked.last().last()) { DropdownMenuButtonGroup() } } } } @Composable private fun DropdownMenuButtonGroup() { ButtonGroup( overflowIndicator = { menuState -> ButtonGroupDefaults.OverflowIndicator(menuState) }, modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterHorizontally), ) { customItem( buttonGroupContent = { FilledIconButton( onClick = {}, colors = IconButtonDefaults.filledIconButtonColors( containerColor = MenuDefaults.groupStandardContainerColor ), ) { Icon(painter = rememberVectorPainter(AppIcons.ThumbUp), contentDescription = "Localized description") } }, menuContent = { DropdownMenuItem( leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.ThumbUp), contentDescription = null) }, text = { Text("Thumbs up") }, onClick = {}, ) }, ) customItem( buttonGroupContent = { FilledIconButton( onClick = {}, colors = IconButtonDefaults.filledIconButtonColors( containerColor = MenuDefaults.groupStandardContainerColor ), ) { Icon(painter = rememberVectorPainter(AppIcons.ThumbDown), contentDescription = "Localized description") } }, menuContent = { DropdownMenuItem( leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.ThumbDown), contentDescription = null) }, text = { Text("Thumbs down") }, onClick = {}, ) }, ) customItem( buttonGroupContent = { FilledIconButton( onClick = {}, colors = IconButtonDefaults.filledIconButtonColors( containerColor = MenuDefaults.groupStandardContainerColor ), ) { Icon(painter = rememberVectorPainter(AppIcons.TagFaces), contentDescription = "Localized description") } }, menuContent = { DropdownMenuItem( leadingIcon = { Icon(painter = rememberVectorPainter(AppIcons.TagFaces), contentDescription = null) }, text = { Text("Emotes") }, onClick = {}, ) }, ) } }
Tài nguyên khác
- Material Design: Trình đơn