How can I add 2 buttons with submenu in Android Studio

0

I'd like to dynamically add options to my screen menu on Android, I've seen several examples, but all turned to a single button.

Assuming I have it.

 override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        menu.clear()

       val menu1 = menu
                .add(Menu.NONE, 1, Menu.NONE, null)
                .setIcon(R.drawable.ic_add_round_white)
               .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

        val menu2 = menu
                .add(Menu.NONE, 2, Menu.NONE, null)
                .setIcon(R.drawable.ic_edit_white)
                .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM) 

}

In this example I can generate 2 buttons to the top bar of my screen, the question is how to increment options inside these buttons?

I use kotlin, but java would solve it.

    
asked by anonymous 16.07.2018 / 20:01

1 answer

1

It is possible to be done yes. Both XML and programmatically.

I recommend taking a closer look at the Android documentation on menus: link

To create the submenus you will have to loot these two MenuItem as sumbenus and add new items to them:

override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
    menu.clear()

   val menuItem1 = menu
            .add(Menu.NONE, 1, Menu.NONE, null)
            .setIcon(R.drawable.ic_add_round_white)
            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

   val subMenu1 = menu.addSubmenu(
                  groupid = 1,
                  itemId = menuItem1.itemId,
                  order = 1,
                  title = "Título")

   val subItem1 = subMenu1
            .add(Menu.NONE, 11, Menu.NONE, null)
            .setIcon(R.drawable.ic_add_round_white)
            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

}

PS: I named the parameters in the addSubmenu function to illustrate the parameters, it is not necessary to have them as well.

There you repeat with the other items. I highly recommend strongly doing this using XML menus and inflate according to need. Because it is much easier to maintain this type of code because the construction is much simpler and divided into layers.

    
18.07.2018 / 15:24