This example uses a Basic Activity type app with a round button (FloatingActionButton) that hovers over the bottom right of the interface.
Creating the popup menu
To create the popup menu it is necessary to first instantiate and then add items before adding a listener (OnMenuItemClickListener) to identify the item clicked. It is also necessary to know the view from which the menu will originate.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); final PopupMenu menu = new PopupMenu(this, fab); menu.getMenu().add("Add Image"); menu.getMenu().add("Add Text"); menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // insert your code here Log.d("menu title: ", item.getTitle().toString()); return true; } } );
Showing the menu
The next step is to attach an OnClickListener to the view that is going to trigger the appearance of the popup menu. Here I use the floating action button to which I attach an OnClickListener with the simply instruction on click that it will show the menu.
fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { menu.show(); } });This is all there is to it, the code can be placed in the onCreate method of your MainActivity for testing.
Comments
Post a Comment