Dynamic control of action/menu items in ActionBar

余生颓废 提交于 2019-12-21 12:04:22

问题


Is there a way to dynamically disable , hide, add/remove menu items in ActionBar ? For example, an action is disabled until user fills a valid phone number in an activity.

I didn't find any useful methods in ActionBar API, the only way seems to be using a custom View in ActionBar.


回答1:


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();



回答2:


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();
    }


来源:https://stackoverflow.com/questions/12419142/dynamic-control-of-action-menu-items-in-actionbar

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