lory105
lory105

Reputation: 6302

Dynamically add action item in action bar

I want to create my action menu items in the ActionBar totally dinamically for some reasons. But when I add the menu items from code, they are displayed as overflow of the setting menu item.

Below there is my code. any solution?

enter image description here

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.start, menu);

    MenuItem logoutMI= menu.add(0,1,0,"Logout");
    logoutMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    logoutMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    MenuItem configMI= menu.add(0,2,1,"Configuration");
    configMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    configMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    return true;
}

Upvotes: 4

Views: 6100

Answers (2)

invertigo
invertigo

Reputation: 6438

Take a look at the order field of your other menu items, you are adding "Logout" and "Configuration" with an order of 0, but if all your other menu items have an order of 0, they will be ordered based on when they were added to the menu.

Also, you will want to call setShowAsAction() only once, with an or operator:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.start, menu);

    MenuItem logoutMI= menu.add(0,1,0,"Logout");
    logoutMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    MenuItem configMI= menu.add(0,2,0,"Configuration");
    configMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    return true;
}

Upvotes: 1

XiaoChuan Yu
XiaoChuan Yu

Reputation: 4011

I think you need to OR those flag values together on setShowAsAction. From the docs, http://developer.android.com/reference/android/view/MenuItem.html#setShowAsAction(int)

One of SHOW_AS_ACTION_ALWAYS, SHOW_AS_ACTION_IF_ROOM, or SHOW_AS_ACTION_NEVER should be used, and you may optionally OR the value with SHOW_AS_ACTION_WITH_TEXT. SHOW_AS_ACTION_WITH_TEXT

Ex.

 logoutMI.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

Let me know if this actually fixed your problem.

Upvotes: 5

Related Questions