תפריטים נפתחים מאפשרים למשתמשים ללחוץ על סמל, שדה טקסט או רכיב אחר, ואז לבחור מתוך רשימה של אפשרויות במשטח זמני. במדריך הזה מוסבר איך ליצור תפריטים בסיסיים ותפריטים מורכבים יותר עם מפרידים וסמלים.
פלטפורמת ה-API
כדי להטמיע תפריטים נפתחים, משתמשים ברכיבים DropdownMenu, DropdownMenuItem, IconButton ו-ExposedDropdownMenuBox. הרכיבים DropdownMenu ו-DropdownMenuItem משמשים להצגת הפריטים בתפריט, ו-IconButton או רכיבים אחרים יכולים להפעיל את הצגת התפריט.
ExposedDropdownMenuBox משמש ליצירת תפריט שמצורף לשדה טקסט.
הפרמטרים העיקריים של הרכיב DropdownMenu הם:
-
expanded: מציין אם התפריט גלוי. -
onDismissRequest: משמש לטיפול בסגירת התפריט. -
content: התוכן הקומפוזבילי של התפריט, שבדרך כלל מכיל רכיבים קומפוזביליים מסוגDropdownMenuItem.
הפרמטרים העיקריים של DropdownMenuItem כוללים:
-
text: מגדיר את התוכן שמוצג באפשרות בתפריט. -
onClick: קריאה חוזרת (callback) לטיפול באינטראקציה עם הפריט בתפריט.
יצירת תפריט נפתח בסיסי
בקטע הקוד הבא אפשר לראות הטמעה מינימלית של DropdownMenu:
@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... */ } ) } } }
מידע חשוב על הקוד
- מגדיר
DropdownMenuבסיסי שמכיל שתי אפשרויות בתפריט. - הפרמטר
expandedקובע אם התפריט יוצג במצב מורחב או מכווץ. - הפרמטר
onDismissRequestמגדיר קריאה חוזרת (callback) שמתבצעת כשהמשתמש סוגר את התפריט. - הרכיב הניתן לTex-
DropdownMenuItemמייצג פריטים שניתן לבחור בתפריט הנפתח. IconButtonמפעיל את ההרחבה והכיווץ של התפריט.
תוצאה
יצירת תפריט נפתח ארוך יותר
כברירת מחדל, אפשר לגלול ב-DropdownMenu אם אי אפשר להציג את כל הפריטים בתפריט בבת אחת. קטע הקוד הבא יוצר תפריט נפתח ארוך יותר שאפשר לגלול בו:
@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... */ } ) } } } }
מידע חשוב על הקוד
- אפשר לגלול ב-
DropdownMenuכשהגובה הכולל של התוכן שלו חורג מהשטח הזמין. הקוד הזה יוצרDropdownMenuשניתן לגלילה ומציג 100 פריטים של פלייסהולדרים. - הלולאה
forEachיוצרת באופן דינמי רכיבים קומפוזביליים מסוגDropdownMenuItem. הפריטים לא נוצרים באופן עצל, כלומר כל 100 הפריטים בתפריט הנפתח נוצרים וקיימים בקומפוזיציה. - ה-
IconButtonמפעיל את ההרחבה והכיווץ של ה-DropdownMenuכשלוחצים עליו. - ה-lambda של
onClickבתוך כלDropdownMenuItemמאפשרת להגדיר את הפעולה שתתבצע כשהמשתמש יבחר פריט בתפריט.
תוצאה
קטע הקוד שלמעלה יוצר את התפריט הבא שניתן לגלילה:
יצירת תפריט נפתח ארוך יותר עם קווי הפרדה
בקטע הקוד הבא מוצגת הטמעה מתקדמת יותר של תפריט נפתח. בקטע הקוד הזה, סמלים בתחילת ובסוף הפריטים נוספים לפריטי התפריט, וקווי הפרדה מפרידים בין קבוצות של פריטי תפריט.
@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... */ } ) } } }
הקוד הזה מגדיר DropdownMenu בתוך Box.
מידע חשוב על הקוד
- הפרמטרים
leadingIconו-trailingIconמוסיפים סמלים להתחלה ולסוף שלDropdownMenuItem. IconButtonמפעיל את הרחבת התפריט.- ה-
DropdownMenuמכיל כמה רכיביDropdownMenuItem, שכל אחד מהם מייצג פעולה שאפשר לבחור. - רכיבי ה-Composable מסוג
HorizontalDividerמוסיפים קו אופקי כדי להפריד בין קבוצות של פריטים בתפריט.
תוצאה
הקטע הקודם יוצר תפריט נפתח עם סמלים ומפרידים:
עדכון ל-M3 Expressive
ב-Material 3 Expressive נוספו האפשרויות DropdownMenuPopup, DropdownMenuGroup ו-CheckableDropdownMenuItem, לצד DropdownMenu ו-DropdownMenuItem, כדי ליצור תפריטים מחולקים עם פריטים מקובצים, מרווחים ומצבים שניתן לסמן.
מידע נוסף על העדכונים של M3 Expressive לתפריטים זמין בהנחיות של Material Design 3 לתפריטים.
תפריטים מפולחים
תפריטים מחולקים מקבצים פעולות קשורות לקטעים חזותיים נפרדים שמופרדים על ידי רווחים או מפרידים. בקטע הקוד הבא אפשר לראות איך מטמיעים תפריט נפתח עם מקטעים באמצעות DropdownMenuPopup, DropdownMenuGroup ו-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 = {}, ) }, ) } }
מקורות מידע נוספים
- Material Design: תפריטים