Adding PopupMenu to an adapter item

In Android, lists tend to have actions associated with them. We can do this via onClick(View v) or event the outdated long press action, but what if we want to give an item in our list a menu style drop-down? Well, this is actually pretty easy to do with the PopupMenu class from Android. So how do we use it?

Since I have received a lot of traffic on my StackOverflow post about just this thing, I have decided to share a quick tutorial on how to add them to your adapter.

Piggybacking off the same repository from our ViewModel and LiveData demo we can easily add a drop-down menu via the PopupMenu class.

First, let’s add the following strings to our strings.xml file:

Then let’s create a menu using these values as our titles:

Next, let’s add a new overflow image button using vector assets:

We are almost done, now we just need to add an AppCompatImageButton to our layout:

Now let’s hook it all up to our adapter code in our onBindView(holder: ViewHolder, position: Int) method!

And there you have it! Your list items will now have a PopupMenu where you can react to the list items overflow button.

Please leave a comment or share if you enjoyed the tutorial.

The full source code is available on Github.


Leave a Reply

Your email address will not be published. Required fields are marked *