how to create a popup menu in android studio (kotlin guide)

How to create PopUp Menu Android | 2022 | Android Studio

A PopupMenu is some form of a menu that is used to display a menu in a modal popup window which is rooted upon a certain view. Example, if you have a login button with multiple login options, you may create this kind of menu there. A popup will appear below the button provided that a room is available, else it shows on top of the view, which for our case is a button. Some cases happen when an IME is visible where we don't expect that a popup will overlap it unless it is brought into an attention, such as when it's clicked. Just like some dialogs you've met, touching outside of the popup will surely dismiss it. 

Let's fire this up by creating a menu in XML and then we definitely will shift our efforts to the Kotlin file where we implement it's usability. The process will be in a couple of steps, very descriptive and simple i tell you that.

Creating a Menu XML for the Popup Menu.

Some people may have this expert ability where they just create the whole thing on their activity's code. I appreciate that, and i think it's an expert thing anyone could do. But hey, hop on with me as we implement the most best practice available. 

How to create a menu directory in android studio

  • First step is for you to move to your res directory and right click on it, select new then navigate to Android Resource Directory, click on it. A window will pick up providing you with input fields such as Directory Name & Resource type, you really don't need to worry about the name right now, you go for the resource type, in the drop down menu choose menu and the name will pick that up as well. Now that we have our menu directory in place, let proceed to creating the actual menu plus it's items.
  • On the menu directory you just created, right click on it and select New, the options will appear where you then should select Menu Resource File. Name it however you like. And this is the actual place where we are going to add our menu items. You may take a look at this sample of mine.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
   
<item android:id="@+id/loginWithFacebook"
         
android:icon="@drawable/ic_facebook"
         
android:title="@string/facebook"
         
android:showAsAction="ifRoom"/>
   
<item android:id="@+id/loginWithGoogle"
         
android:icon="@drawable/ic_google"
         
android:title="@string/google" />
</menu>

i suppose, you create vector assets of your own to use as the icons. And there! we have a menu in place. So we are free to proceed to the Activity's area and do some maneuvers. But wait, i know that i previously discouraged to stress all of this task of creating a pop up menu on an Activity's Code (for our case, Kotlin) let's see why it's actually important to deploy an XML in the process.

  • As you are creating your menu, it becomes relatively simpler to visualize the menu structure in XML. We all can agree on this, as the utility provides a code tab and a design tab as well
  • As a common feature for all programmers, we need abstraction at some point.  And so through this practice we can separate the content of our menu from your code flow in your Activity's Kotlin files.
  • It allows you to create alternative menu configurations for different platform versions, screen sizes, and other configurations by leveraging the app resources framework.

 Instantiate a Popup Menu

The heading above is just a fancy way to say, Create an Object for the Popup Menu. How do we do it?, well we simply use the already available PopupMenu Constructor, only that we require a context for this plus the view on which our menu is going to stick it's roots on. If you can recall, my analog was based on a button that has multiple login options. So it surely is the button that we are going to pass as the view here.

Make use of MenuInflater

Remember that we recently have created a Menu Resource?. Well here is the actual place we are going to enjoy the fruits of our effort we just invested a couple of minutes ago. Use MenuInflater to inflate our menu we created to an object that is normally returned by PopupMenu.getMenu() namely Menu. And please don't start getting worried about the sample code, am simply elaborating this in general and then I'll drop out a bunch of codes with respect to what i am saying right now. 

Call the Popup Menu into action

So, finally we need to call the menu into action simply by using show() which should be preceded by what i would like to call a Constructor for the menu. Use PopupMenu.show() to do this.  The call to action is very important because if you don't, you wont successfully be able to see the PopupMenu. 

Take a look at my sample code below, at least to visualize what i have actually been narrating about

fun showPopup(B: View) {
   
val popup = PopupMenu(this, B)
   
val inflater: MenuInflater = popup.menuInflater
    inflater
.inflate(R.menu.actions, popup.menu)
    popup
.show()
}

A handy usability for cases you are targeting android API level 14 or above is that you can simplify the lines of code which do the job of inflating the menu only by writing PopupMenu.inflate(). If i can recall correctly, there is a point where i said, the menu will disappear if you touch anywhere outside the menu or obviously when you click on the menu item.

Implementing ClickListener 

It makes a more perfect sense if you have menu items that actually do a thing. Picture a menu that provides you a variety of options and totally does nothing when you click on any of the items (it's boring). So let's get together and make sure we implement some actions depending on user selections.

To bring about this functionality, you need to have an interface in place, this interface is in the form of PopupMenu.OnMenuItemClickListener. You then will need to make PopupMenu aware of what is really happening by simply calling the setOnMenuItemClickListener()  where by as user selects any of the menu item, the system calls onMenuItemClick() callback.

fun showMenu(v: View) {
   
PopupMenu(this, v).apply {
       
// MainActivity implements OnMenuItemClickListener
        setOnMenuItemClickListener
(this@MainActivity)
        inflate
(R.menu.menuName)
        show
()
   
}
}

override fun onMenuItemClick(item: MenuItem): Boolean {
   
return when (item.itemId) {
        R
.id.loginWithFacebook -> {
          //do something
here
           
true
       
}
        R
.id.loginWithGoogle -> {
            //do something here

           
true
       
}
       
else -> false
   
}
}

 That's all we need to do to implement our fancy Popup Menu. Hope this article was helpful, leave me your comments if any. And please feel free to go around and read through other articles you find usefull

Stay awesome,

#Stanley

 

0 Comments