Popupmenu filling without XML file in android

I have this code, this works fine. Only I want to make this dynamic without an xml file (actions.xml). How to do it?

public void showPopup(View v) { PopupMenu popup = new PopupMenu(this, v); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.actions, popup.getMenu()); popup.show(); } 
+7
source share
2 answers

Use popup.getMenu() , and then add the elements directly using various add overloads.

+5
source

in the xml file, delete unused elements (only for implementing the menu theme). So it will look like this:

 <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:theme="@style/AppTheme" /> 

then use getMenu to add new menu items as shown below:

 Button btn1= (Button) findViewById(R.id.btn_test); PopupMenu popup = new PopupMenu(yourFormName.this, btn1); //Inflating the Popup using xml file popup.getMenu().add("Menu1 Label"); popup.getMenu().add("Menu2 Label"); popup.getMenuInflater().inflate(R.menu.YourXMLFileName, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { //---your menu item action goes here .... Toast.makeText(DisplayTransactions.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show(); return true; } }); popup.show();//showing popup menu 
+2
source

All Articles