Programming and Personal Development

Android Popup Menus

Popup menus in android are useful for displaying extended options associated with a specific action. For eg: ‘send’ action could have multiple extended options, like ‘send by email’ or ‘send by sms’ etc. Unlike android context menus they can be invoked by any event such a button click not just long clicks. They are associated with the specific view that invoked it and each view in an activity can have its own popup window.

Steps to create a Popup menu

  • Create a new instance of PopupMenu class and pass the instance of the Context ( usually the current activity) and the view (for which the pop-up menu is desired) as arguments.
  • Inflate the menu resource using:
    • popupMenu.inflate () if you are using Android 4.0 SDK and above (or)
    • MenuInflater class (popupMenu.getMenuInflater().inflate() method) if you are using Android 3.0 SDK
  • Call popupMenu.show() to display the menu

Responding to menu item selections

Override the popupMenu.setOnMenuItemClickListener () method and provide a call back for handling user selections. The use selected menu item is passed in as argument to the callback method.

Example

Android popup menu exampleLets adapt the same example we saw for the android context menu previously to use popup menus instead. What we have here is a single button that is wrapped inside a linear layout. Clicking the button invokes a popup menu that lets us change the background color for the button as shown in the sample screenshot.

Menu resource File

This is the same color menu resource file under res/menu folder that we used in android context menu example.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_red" android:title="Red" />
    <item android:id="@+id/menu_green" android:title="Green"/>
    <item android:id="@+id/menu_blue" android:title="Blue"/>
</menu>

Layout definition file

One single button within a linear layout.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button android:id="@+id/popupMenuBtn"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Show me the Popup"
            android:layout_gravity="center"
            android:gravity="center"/>
</LinearLayout>

Java Source Code

Nothing fancy here again. We just follow the 3 steps mentioned above for creating a context menu and define the menu handler to handle user selections.

  • The button element acts as the view responsible for invoking the popup menu. Create a new instance of the popup menu and pass the activity and the button as arguments
  • Inflate the menu resource and associate it with the popup menu instance.
  • Call popupmenu.show () method within the onClick listener to display the menu when the user clicks the button.
  • Override the popupMenu.setOnMenuItemClickListener () method to change the background color of the button based on user selections.
public class MenuDemo extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menudemo);
        /**
         * A Button that acts as the view element for the popup menu.
         */
        final Button btn = (Button) findViewById(R.id.popupMenuBtn);
        /**
         * Step 1: Create a new instance of popup menu
         */
        final PopupMenu popupMenu = new PopupMenu(this, btn);
        /**
         * Step 2: Inflate the menu resource. Here the menu resource is
         * defined in the res/menu project folder
         */
        popupMenu.inflate(R.menu.color_menu);
        /**
         * Step 3: Call show() method on the popup menu to display the
         * menu when the button is clicked.
         */
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupMenu.show();
            }
        });
        /**
         *  Handle menu item clicks
         */
        popupMenu.setOnMenuItemClickListener(
                new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_red:
                        btn.setBackgroundResource(R.color.LightRed);
                        break;
                    case R.id.menu_blue:
                        btn.setBackgroundResource(R.color.DullBlue);
                        break;
                    case R.id.menu_green:
                        btn.setBackgroundResource(R.color.LightGreen);
                        break;
                }
                return true;
            }
        });

    }
}

 

Happy Coding !!!

Android Context Menus

Context menus are invoked in android when user performs a long click ( click and hold). While the Options menu is associated with a specific activity, context menus are associated with specific views within the activity. Thus an activity can have only one options menu but many context menus. Context Menu Creation To create aContinue Reading

Android Menus Part 1

Every activity in android is associated with a menu. Menus in turn contain menu items and other sub menus. As of android 4.0 ( icecream sandwich), following are the  types of menus available to the developer. Options menu:  Options menu show up when the user clicks on the menu button present in the android devicesContinue Reading

Android Gallery

Along with ListViews and Spinners, android also provides a Gallery widget that are useful for displaying a list of elements. Unlike the other two where elements are displayed vertically, Gallery lets you scroll through the elements horizontally.   You specify the items to be displayed in the gallery through an adapter and can register callbacksContinue Reading

Customizing Android WebView

In previous post we saw how to use the default Webview element to display html resources in your android application . Webview also offers the ability to override its default content loading behaviour, look and feel and its settings to suit your needs. Lets look at the various  customization points with examples. WebViewClient Allows youContinue Reading

Display Web Pages in your android application

Webview extends the View class and is useful for displaying a web page  as part of your activity. By default it behaves like a browser minus things like navigation controls, address bar etc. Even javascript is disabled with the default settings. You can use it to display things like help files , end-user agreements, FAQsContinue Reading

Android Spinner

Spinners are the Dropdown widget equivalent in android.  They are useful for displaying the list of items especially when the available screen real estate is less. Only the selected item is shown while the rest are hidden. Clicking on the spinner results in a drop down list showing the list contents. Just as with ListViews you haveContinue Reading

Android ListView Part 3

In part 2 of the series, we discussed how android’s ArrayAdapter class internally reuses views to optimize performance. However reusing views has the side effect of losing any state associated with the current data, as the view is recycled andupdated with new data. Lets say, we want to change the appearance of the text when the userContinue Reading

Android ListView Part 2

In part1 of this series, you learned what an adapter is and how it can be used to feed a simple ListView element.  Continuing from there, lets learn how to make some useful customizations to the ListView and a trick that android uses to optimize the usage of ListView elements for better performance. MultiChoiceMode Lets start withContinue Reading

Android ListView Part1

As the name suggests, ListViews are useful for displaying a scrollable list of items to the user. The items can be of any of the standard types like String or custom user defined types. It lets the users select one or more elements from the list and provides listeners to track change in selections.  ButContinue Reading

Web Analytics