Dynamically add action item in action bar

一曲冷凌霜 提交于 2019-12-04 12:49:27

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.

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!