2012-03-05 10 views
7

Tengo este código, esto funciona perfecto. Solo quiero hacer esto dinámico sin el archivo xml (actions.xml). ¿Cómo puedo hacer eso?Completar menú emergente sin archivo XML en android

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

Respuesta

5

Uso popup.getMenu() y luego añadir elementos utilizando directamente las distintas sobrecargas de add.

+1

Niza TNX :) ¿Sabe usted cómo configurar el estilo de ¿¿Menú emergente?? – Mitch

+1

No sé cómo hacer eso específicamente, no. Puede consultar [estos] (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

+1

¿Alguien más? – Mitch

2

en el archivo xml eliminar elementos no utilizados (solo para implementar el tema del menú). Por lo tanto, será como:

<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" /> 

a continuación, utilizar getMenu añadir nuevos elementos de menú de la siguiente manera:!

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 
Cuestiones relacionadas