Dynamic control of action/menu items in ActionBar

风流意气都作罢 提交于 2019-12-04 04:08:33

To tell ActionBar to refresh its menu items: invalidateOptionsMenu()

then to enable/disable Menu Items:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item= menu.findItem(R.id.men_1);
    //depending on your conditions, either enable/disable
    item.setEnabled(false);
    super.onPrepareOptionsMenu(menu);
    return true;
}

and to hide the action bar you have:

getActionBar().hide();

Another option: having a field in the Activity storing the Menu. This way it's possible to call getMenuInflater().inflate() and menu.clear() from anywhere you want in this activity

So, it looks something like this:

class MyActivity extends ActionBarActivity {

    Menu actionBar;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        actionBar = menu;
        return true;
    }

    //Possible usage
    void showActionBar1 () {
        getMenuInflater().inflate(R.menu.menu_1, actionBar);
        actionBar.findItem(R.id.menu_1_btn_1).setOnMenuItemClickListener();
    }

    void showActionBar2 () {
        getMenuInflater().inflate(R.menu.menu_2, actionBar);
        ...
    }

    void clearActionBar () {
        if (actionBar != null) actionBar.clear();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!