Android Adventures - Menus, Context & Popup
Written by Mike James   
Tuesday, 26 May 2015
Article Index
Android Adventures - Menus, Context & Popup
Contextual Action Mode
Popup Menu

The Popup Menu

The final menu is so simple by comparison with the rest it is hardly necessary to explain how to implement it!

What is more difficult is to say when it should be used. It certainly shoudn't be used as a substitute for a context menu where the operations affect the content that it is "attached" to. In the case of a popup it seems that its common uses are to refine an action selection by providing parameters that modify it. 

To show a popup menu all you have to do is instantiate a PopupMenu object, set its onMenuItemClick event handler, create the menu by say inflating a resource file and finally using its show method. Where on the screen the PopupMenu shows depends on the View object you pass when creating the instance.

The steps are:

  1. Create an instance of PopupMenu and pass the View object you want to use to position the menu. 

  2. If you want to handle item selection override the onMenuItemClick method. 

  3. Use the instance's inflate method to create the menu

  4. Use the instance's show method to show the menu.

A popup menu is usually shown in response to some user action and so we need an event handler to create the popup in. If you place a button into the UI you can define its click event handler as: 

Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(
 new View.OnClickListener() {
     @Override
     public void onClick(View v) {
     PopupMenu popup=
             new PopupMenu(v.getContext(),v);
     popup.inflate(R.menu.mycontext);
     popup.show();
    }
});

The onClickPopup will be called when the button is clicked.

The PopupMenu constructor accepts the context and the View object it will be displayed next to. Usually this is the View object that the user clicked or interacted with i.e. the button in this case. Next we inflate the menu as usual but using the Popups own inflater which adds the menu to the Popup. Finally we call show which displays the Popup:

 

popup2

 

The menu is immediately dismissed if the user clicks on an item or on any other part of the display. 

Of course if you were really using the popup menu you would also handle the item click event:

popup.setOnMenuItemClickListener(
  new PopupMenu.OnMenuItemClickListener() {
  @Override
  public boolean onMenuItemClick(
                           MenuItem item) {
   TextView tv=
   (TextView) findViewById(R.id.textView2);
   tv.setText(item.getTitle());
   return false;
  }
});

Again you can get Android Studio to generate the stub using the Code,Generate command. As before you would use a select to discover which item the user had selected and act on that selection.

The complete code is:

Button button=
      (Button) findViewById(R.id.button);
button.setOnClickListener(
             new View.OnClickListener() {
 @Override
 public void onClick(View v) {
  PopupMenu popup=
         new PopupMenu(v.getContext(),v);
  popup.inflate(R.menu.mycontext);
  popup.setOnMenuItemClickListener(
   new PopupMenu.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(
                            MenuItem item) {
    TextView tv=
     (TextView) findViewById(R.id.textView2);
    tv.setText(item.getTitle());
    return false;
   }
  });
  popup.show();
 }
});

 

Summary

  • The context menu is invoked for all View objects in the UI that are registered using registerForContextMenu(View).

  • When the user long clicks on any registered object the onCreateContextMenu and you can use this to display the menu. When the user selects any of the items in the menu the system the onContextItemSelected event handler is called.

  • The contextual action mode menu is the most complicated to implement. You have to create an ActionMode.Callback object complete with methods to create the menu and handle events from its items.

  • To display the menu you call the startSupportActionMode(Callback) specifying the Callback object to be used.

  • If you want to use the contextual action mode menu on earlier versions of Android you have to use the support library classes.

  • The popup menu is the easiest to use. Simply create a Popup object, inflate the menu resource and use its show method to display the menu.

Where Next?

The subject of menus and how to use them is a big one and this is really just a basic introduction to the idea. From here you can learn about how to group menu items together, how to put check boxes and even completely general View objects into menus. Then there is the whole subject of using context menus with more complex data such s lists. 

All of which build on what this chapter has described. 

 

You can download the code for this program and for the simple blank activity template from the CodeBin (note you have to register first).

 

androidJavaSmallAndroid Programming In Java:
Starting With an App
Third Edition

Is now available in paperback and ebook.

Available from Amazon.

 

 

  1. Getting Started With Android Studio 3
  2. The Activity And The UI
  3. Building The UI and a Calculator App
  4. Android Events
         Extract: Using Lambdas
  5. Basic Controls
  6. Layout Containers
  7. The ConstraintLayout
        Extract: Guidelines and Barriers
  8. UI Graphics A Deep Dive
        Extract: Programming the UI ***NEW
  9. Menus & The Action Bar
  10. Menus, Context & Popup
  11. Resources
  12. Beginning Bitmap Graphics
        Extract: Simple Animation
  13. Staying Alive! Lifecycle & State
  14. Spinners
  15. Pickers
  16. ListView And Adapters

If you are interested in creating custom template also see:

Custom Projects In Android Studio

Androidgears

 

 

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter,FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

 

espbook

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Monday, 10 October 2016 )