Home > Software design >  How to make a button a menu trigger in Jetpack Compose?
How to make a button a menu trigger in Jetpack Compose?

Time:03-23

I tried adding an IconButton() and wanted to click the button to turn it on or off (while also clicking elsewhere to dismiss it)

But a funny qustion happend.

The trigger button is included in "Other Places", when I click the button to close the menu, this triggers onDismissRequest() first, and then triggers the button's onClick(), which makes me unable to close the menu (when clicked will instantly close and then open again)

Scaffold(
    ...
    topBar = {
        TopAppBar(
            ...
            actions = {
                var menuExpanded by remember { mutableStateOf(false) }

                Box {
                    IconButton(onClick = { menuExpanded = !menuExpanded}) {
                        Icon(
                            painter = painterResource(id = R.drawable.menu),
                            contentDescription = "menu",
                            tint = white
                        )
                    }

                    DropdownMenu(
                        expanded = menuExpanded,
                        properties = PopupProperties(),
                        onDismissRequest = { menuExpanded = false }
                    ) {
                        // items
                    }
                }
            }
        )
    }
) { ... }

I know I can set Modifier.offset() so that menu masks the button, but I don't want to do that.

What should I do?

CodePudding user response:

This is what PopupProperties.focusable is for: true value prevents other views from getting tapped while the menu is open. By the way, this is the default value if you don't specify properties option.

DropdownMenu(
    expanded = menuExpanded,
    properties = PopupProperties(focusable = true),
    onDismissRequest = { menuExpanded = false }
) {
  • Related