How can I add 2 submenu buttons in Android Studio

Asked

Viewed 207 times

-1

I would like to add dynamically options to my screen menu on Android, I saw several examples, but all facing a single button.

supposing that I have.

 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 doubt is how to increment options within these buttons?

I use Kotlin, but java would already solve.

  • It is not better you create the layout on menu.xml and overwrite the method onPrepareOptionsMenu changing only the visibility of the items you want to appear?

  • No, because the options are based on what the API provides me, which can change dynamically ;(

1 answer

1

It is possible to do yes. Both by XML and programmatically.

I recommend taking a deep look at the Android documentation on menus: https://developer.android.com/guide/topics/ui/menus?hl=pt-br

To create the submenus you will have to associate these two of yours 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 function addSubmenu to illustrate the parameters, it is not necessary to have them like this.

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

  • I understood your example, but in this case as I could also add a menu of options to the first button, in this part that float. It needs to be programmatically because the options provided by the API, based on access, summarizing are 2 buttons in the action bar and these 2 buttons have several options.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.