8

I have this code, this works perfect. Only i want to make this dynamic without the xml file(actions.xml). How do i do that?

public void showPopup(View v) {
    PopupMenu popup = new PopupMenu(this, v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.actions, popup.getMenu());
    popup.show();
}
Mitch
  • 133
  • 2
  • 5

2 Answers2

7

Use popup.getMenu() and then add items directly using the various overloads of add.

kabuko
  • 36,028
  • 10
  • 80
  • 93
  • 2
    Nice tnx!:) Do you know how to set the style of PopupMenu?? – Mitch Mar 05 '12 at 22:04
  • 2
    I don't know how to do that specifically, no. You might look at [these](http://stackoverflow.com/questions/3142067/android-set-style-in-code) [related](http://stackoverflow.com/questions/8369504/why-so-complex-to-set-style-from-code-in-android) [questions](http://stackoverflow.com/questions/2016249/how-to-programmatically-setting-style-attribute-in-a-view). – kabuko Mar 05 '12 at 22:37
  • How to get selected value? – Igor Janković Apr 16 '19 at 12:24
3

in the xml file remove unused items (just to implement menu theme). So, it'll be like :

<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 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  
Hussein mahyoub
  • 335
  • 4
  • 6