How can I dismiss a `DropdownMenu` when it is clic...
# compose
c
How can I dismiss a
DropdownMenu
when it is clicked? Is the only way through
DropdownMenuItem
via its
onClick
? I’ve tried passing
DropdownMenu(modifier = Modifier.clickable …)
but this doesn’t have any effect that I can see.
I assume the click is being consumed by the
DropdownMenuItem
a
Whether the menu is showing or not is entirely controlled by the
expanded
parameter passed to
DropdownMenu
. For the simplest case, you probably want to have
onDismissRequest
and item clicks update a state that results in
DropdownMenu(expanded = false)
c
Thanks for responding Alex. I know how the component works generally, and how it can be dismissed. The reason I ask this question is I have an overflow menu as dropdown. The dropdown contains a fixed list of items like this:
Copy code
var expanded by remember { mutableStateOf(false) }
// There is a clickable icon with onClick = { expanded = true }

DropdownMenu(expanded = expanded, ...) {
  DropdownMenuItem(
    onClick = {
      expanded = false
      onSelectAllClick()
    }
  ) {
      Text("Select All")
  }

  DropdownMenuItem(
    onClick = {
      expanded = false
      onSelectNoneClick()
    }
  ) {
      Text("Select None")
  }

  DropdownMenuItem(
    onClick = {
      expanded = false
      onRefreshListClick()
    }
  ) {
      Text("Refresh List")
  }
}
Each of the
DropdownMenuItem
onClick
handlers must dismiss the
DropdownMenu
I’m wondering if this can be handled in one place
Is it better in this case to just model the menu items and loop over them like
Copy code
listOf(selectAll, selectNone, refreshList).forEach { menuItem ->
  DropdownMenuItem(...)
}
Tbh it seems overkill for such a simple menu. But I’d be curious to know what is idiomatic here
a
You could do something like that, or some sort of
hideMenuAnd(lambda: () -> Unit)
. But agreed, I think that’s still pretty overkill. I think what you originally have is straightforward. It might be a bit more verbose, but it’s crystal clear what’s going on.
c
Yeah overall I like how Compose is explicit, there’s just the odd case like this where there’s a bit of duplication. I might wrap it in a
hideMenuAnd
lambda as you suggest.
620 Views