Buttons on Android ActionBar

1

I am creating an application and I need to put buttons in the ActionBar and I already did it but I do not know how to put images on the buttons and only text (see image) the question is that in XML if it is done but in this case I can not use XML, just Java, any ideas on how to do it with Java alone?

Code that I am using (this is also the one of the overflow menu):

android.support.v7.widget.SearchView searchview;

ArrayAdapter<String> adapter;
@Override
public boolean onCreateOptionsMenu (Menu menu){
   menu.add(0, 0, 0, "Notificar");
   menu.add(0, 1, 1, "Test de velocidad");
   menu.add(0, 2, 2, "Salir");
   menu.add(0,3,3,"Refrescar").setActionView(searchview).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
   menu.add(0,4,4,"Ayuda").setActionView(searchview).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
   return true;
}

    
asked by CarlosSera 26.11.2018 в 22:04
source

1 answer

0

Assuming you already have the icons in res->drawable

@Override
public boolean onCreateOptionsMenu (Menu menu){
    menu.add(0, 0, 0, "Notificar");
    menu.add(0, 1, 1, "Test de velocidad");
    menu.add(0, 2, 2, "Salir");
    menu.add(0, 3, 3, "Refrescar").setActionView(searchview).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    menu.add(0, 4, 4, "Ayuda").setActionView(searchview).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

   // Agrega esto
   // Menú para Notificar
   menu.getItem(0).setIcon(R.drawable.ic_notifications_icon);

  // Menú para test de velocidad
   menu.getItem(1).setIcon(R.drawable.ic_speedtest_icon);
   ...

   // Eso es para que visualice los iconos en el overflow menu
   if(menu instanceof MenuBuilder) {
        MenuBuilder m = (MenuBuilder) menu;
        m.setOptionalIconsVisible(true);
    }

   return true;
}

The parameter 0 of getItem() tells you the menu index, for example to notify is 0 , for speed test is 1 , etc.

Edited I added a few more lines of code, the reason is that by researching I realized that the overflow menus appear without icons.

    
answered by 26.11.2018 / 23:46
source