메뉴

드롭다운 메뉴를 사용하면 사용자가 아이콘, 텍스트 필드 또는 기타 구성요소를 클릭한 다음 임시 표시 경로의 옵션 목록에서 선택할 수 있습니다. 이 가이드에서는 기본 메뉴와 구분선 및 아이콘이 있는 더 복잡한 메뉴를 만드는 방법을 설명합니다.

두 가지 옵션이 표시된 드롭다운 메뉴 세로로 된 점 3개 아이콘을 클릭하면 메뉴가 열립니다.
그림 1. 두 항목이 나열된 기본 드롭다운 메뉴

API 노출 영역

DropdownMenu, DropdownMenuItem, IconButton, ExposedDropdownMenuBox 구성요소를 사용하여 드롭다운 메뉴를 구현합니다. DropdownMenu 및 DropdownMenuItem 구성요소는 메뉴 항목을 표시하는 데 사용되며 IconButton 또는 기타 구성요소는 메뉴 표시를 트리거할 수 있습니다. ExposedDropdownMenuBox는 텍스트 필드에 연결된 메뉴를 만드는 데 사용됩니다.

DropdownMenu 구성요소의 주요 매개변수는 다음과 같습니다.

  • expanded: 메뉴가 표시되는지 여부를 나타냅니다.
  • onDismissRequest: 메뉴 닫기를 처리하는 데 사용됩니다.
  • content: 메뉴의 구성 가능한 콘텐츠로, 일반적으로 DropdownMenuItem 컴포저블을 포함합니다.

DropdownMenuItem의 주요 매개변수는 다음과 같습니다.

  • text: 메뉴 항목에 표시되는 콘텐츠를 정의합니다.
  • onClick: 메뉴의 항목과의 상호작용을 처리하는 콜백입니다.

기본 드롭다운 메뉴 만들기

다음 스니펫은 최소한의 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 매개변수는 사용자가 메뉴를 닫을 때 실행되는 콜백을 정의합니다.
  • DropdownMenuItem 컴포저블은 드롭다운 메뉴에서 선택 가능한 항목을 나타냅니다.
  • IconButton는 메뉴의 펼치기 및 접기를 트리거합니다.

결과

그림 2. 옵션이 두 개뿐인 최소한의 드롭다운 메뉴

더 긴 드롭다운 메뉴 만들기

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는 콘텐츠의 총 높이가 사용 가능한 공간을 초과할 때 스크롤할 수 있습니다. 이 코드는 100개의 자리표시자 항목을 표시하는 스크롤 가능한 DropdownMenu을 만듭니다.
  • forEach 루프는 DropdownMenuItem 컴포저블을 동적으로 생성합니다. 항목은 지연 생성되지 않습니다. 즉, 100개의 드롭다운 항목이 모두 생성되어 컴포지션에 존재합니다.
  • IconButton는 클릭 시 DropdownMenu의 펼치기 및 접기를 트리거합니다.
  • 각 DropdownMenuItem 내의 onClick 람다를 사용하면 사용자가 메뉴 항목을 선택할 때 실행되는 작업을 정의할 수 있습니다.

결과

위의 코드 스니펫은 다음과 같은 스크롤 가능한 메뉴를 생성합니다.

그림 3. 스크롤 가능한 긴 드롭다운 메뉴

구분선이 있는 긴 드롭다운 메뉴 만들기

다음 스니펫은 드롭다운 메뉴의 고급 구현을 보여줍니다. 이 스니펫에서는 선행 및 후행 아이콘이 메뉴 항목에 추가되고 구분선이 메뉴 항목 그룹을 구분합니다.

@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... */ }
            )
        }
    }
}

이 코드는 Box 내에 DropdownMenu를 정의합니다.

코드에 관한 핵심 사항

  • leadingIcon 및 trailingIcon 매개변수는 DropdownMenuItem의 시작과 끝에 아이콘을 추가합니다.
  • IconButton는 메뉴 펼치기를 트리거합니다.
  • DropdownMenu에는 여러 DropdownMenuItem 컴포저블이 포함되어 있으며, 각 컴포저블은 선택 가능한 작업을 나타냅니다.
  • HorizontalDivider 컴포저블은 가로선을 삽입하여 메뉴 항목 그룹을 구분합니다.

결과

위의 스니펫은 아이콘과 구분선이 있는 드롭다운 메뉴를 생성합니다.

그림 4. 선행 및 후행 아이콘이 있는 섹션으로 나뉜 드롭다운 메뉴

M3 스타일 업데이트

Material 3 Expressive는 DropdownMenu 및 DropdownMenuItem와 함께 DropdownMenuPopup, DropdownMenuGroup, CheckableDropdownMenuItem를 추가 옵션으로 도입하여 그룹화된 항목, 간격, 선택 가능한 상태가 있는 분할된 메뉴를 만듭니다.

M3 표현 메뉴 예시
그림 5. 간격(1, 왼쪽)과 구분선(2, 오른쪽)이 있는 Material 3 Expressive 세로 메뉴 변형

메뉴의 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 = {},
                )
            },
        )
    }
}

추가 리소스