简体   繁体   中英

Menuitems in my Fragments do not change according to the code for the first time I access Activity

I am using ActionBarActivity with Fragments.

I have already changed the implementation of how menu items must show in actionbar too many times. For example, changing the local of onCreateOptionsMenu to Activity and Fragments.

The first fragment must not show the menu items and another fragment must show one more menu item. Others fragments show the menuitems normally.

The problem: when I enter in the activity for the first time the menu items don't show in any fragment. If I rotate the device everything works fine.

In my others attempts, the behaviour change to: when I enter in the activity for the first time the menu items show in all fragments (the first one has setHasOptionsMenu(false);). And the fragment that have one more menuitem don't show it.

Sorry for bad English.

Working code (after rotate the device):

FirstFragment:

    public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    int count = menu.size();
    for (int i = 0; i < count; i++) {
        menu.getItem(i).setVisible(false);
    }
    }

MainActivity:

public boolean onCreateOptionsMenu(Menu menu) {
    for (int i = 0; i < itens.size(); i++) {
        item = (Item) itens.get(i);

        MenuItem mMenuItem = menu.add(0, i, i, item.getLabel()).setIcon(item.getImage());
        MenuItemCompat.setShowAsAction(mMenuItem, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
    }
    return super.onCreateOptionsMenu(menu);
}

I used it in the constructor:

setHasOptionsMenu(false);

but it didn't work. Then I used it in other method called in the constructor toghether with codes to reflesh the fragment and it works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM