There is a method to handle clicking a menu item in the ToolBar :

  public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.selection_list_goto: // Отсюда хочу вывести Popup menu строкой // PopupMenu popupMenu = new PopupMenu(Contex, View); break; 

but I do not understand what to set as a View , and what about as a Contex or how to display PopupMenu when the button is pressed?

  • Where do you have to obrat him? In the center of the screen or below? Or right upstairs? - Android Android
  • In the center above - Igor
  • The second parameter means "For which view to arrange the menu." Here you need to transfer the object to which it will bind - Android Android
  • How to get ToolBar view? - Igor
  • What you need to specify that the window is displayed above the ToolBar? - Igor

1 answer 1

The documentation is quite accessible, detailed, and even in Russian, the creation of an item of menu with a drop-down list is described - in general, it is enough to hang the listener on the desired View :

Create an item in OptionsMenu , for which you need to display PopupMenu when clicked (the difference is that we hang the listener on the android:onClick ):

 <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_selection_list_goto" android:onClick="showPopup" /> 

Create a method that handles a click on an item placed in OptionsMenu :

 public void showPopup(View v) { PopupMenu popup = new PopupMenu(this, v); popup.setOnMenuItemClickListener(this); popup.inflate(R.menu.popupMenu); popup.show(); } // действие при кликах в созданном PopupMenu @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.archive: archive(item); return true; case R.id.delete: delete(item); return true; default: return false; } } 

where R.menu.popupMenu is a resource for PopupMenu .
R.id.archive , R.id.delete - Aidish points in the PopupMenu resource PopupMenu

PS: if this is unavailable for some reason, in this case you can use the context of the View itself to get the context by getting it using the getContext() method. For example:

  PopupMenu popup = new PopupMenu(v.getContext(), v); 

You can also enter from the other side - do not create a separate method for processing a click (although this is simpler), but get the View from the OnOptionsItemSelected OnOptionsItemSelected :

 public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.selection_list_goto: View v = item.getActionView(); PopupMenu popup = new PopupMenu(v.getContex(), v); popup.inflate(R.menu.popupMenu); popup.show(); break; 

but I did not check this method.