Alexei Artsimovich
Alexei Artsimovich

Reputation: 1184

Android Popup menu Header

I am using the PopupMenu from the androidx.appcompat.widget package (See the pic). Just curious if there is any simple way to set a header to the popup. Or change the alpha of the first menu item and disable ripple effect for it so it's not clickable and looks like a title. Any ideas?

Thanks in advance.PopupMenu

Upvotes: 6

Views: 1648

Answers (1)

Arts
Arts

Reputation: 399

It's been a time since this question was asked, but I had the same question and maybe somebody would find my solution useful.

PopupMenu(requireContext(), anchorView).apply{
   //==== Popup title, non-selectable
   menu.add(Menu.NONE, -1, 0, "Popup Title").apply {
        isEnabled = false }

   //==== Popup items
   menu.add(Menu.NONE, 1, 1, "First selectable item")
   menu.add(Menu.NONE, 2, 2, "Second selectable item")
   menu.add(Menu.NONE, 3, 3, "Third selectable item")

   //==== Selected item callback
   setOnMenuItemClickListener {item ->
      // Whatever you need to do according to the selected item.itemId
      // ...
      return@setOnMenuItemClickListener true
   }
   show()
}

The important moments are:

  1. Set isEnabled = false for the item you want to look like a header (in my case it is non-selectable and light grey)
  2. Set the order parameter to the "header" item less than any order parameter to other items.

If you inflate your Popup Menu from xml set the following attribute to the "header item": android:enabled="false"

Upvotes: 4

Related Questions