メニュー

プルダウン メニューを使用すると、ユーザーはアイコン、テキスト フィールド、またはその他のコンポーネントをクリックして、一時的なサーフェス上のオプションのリストから選択できます。このガイドでは、基本的なメニューと、仕切りやアイコンを含むより複雑なメニューを作成する方法について説明します。

2 つのオプションが表示されたプルダウン メニュー。縦に 3 つ並んだ点のアイコンは、クリックするとメニューが開くことを示します。
図 1. 2 つの項目がリストされた基本的なプルダウン メニュー。

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

コードに関する主なポイント

  • 2 つのメニュー項目を含む基本的な DropdownMenu を定義します。
  • expanded パラメータは、メニューの表示を、展開または折りたたみのいずれかに制御します。
  • onDismissRequest パラメータは、ユーザーがメニューを閉じたときに実行されるコールバックを定義します。
  • DropdownMenuItem コンポーザブルは、プルダウン メニューで選択可能な項目を表します。
  • IconButton は、メニューの展開と折りたたみをトリガーします。

結果

図 2. 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 の更新の詳細については、マテリアル デザイン 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 = {},
                )
            },
        )
    }
}

参考情報