简体   繁体   English

我第一次访问“活动”时,“片段”中的菜单项不会根据代码更改

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

I am using ActionBarActivity with Fragments. 我正在使用带有片段的ActionBarActivity。

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. 例如,将onCreateOptionsMenu的本地更改为Activity和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);). 在我的其他尝试中,行为更改为:当我第一次进入活动时,菜单项显示在所有片段中(第一个片段具有setHasOptionsMenu(false);)。 And the fragment that have one more menuitem don't show it. 而且具有另一个menuitem的片段不显示它。

Sorry for bad English. 对不起,英语不好。

Working code (after rotate the device): 工作代码(旋转设备后):

FirstFragment: 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. 然后,我在构造函数中调用的其他方法中使用了它,并与代码一起刷新了片段,它现在可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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