隐藏/显示不同片段的动作栏选项菜单项

时间:2023-01-16 12:33:46

I have a Sherlock Fragment Activity in which there are 3 Fragments.

我有一个夏洛克片段活动,里面有3个片段。

Fragment A, Fragment B, Fragment C are three fragments. I want to show a done option menu in Fragment B only.

片段A,片段B,片段C是三个片段。我想只在片段B中显示一个完成选项菜单。

And the activity is started with Fragment A. When Fragment B is selected done button is added.

使用片段a启动活动。选择片段B时,添加done按钮。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if(!menusInflated){
        inflater.inflate(R.menu.security, menu);
        menusInflated=true;
    }

    super.onCreateOptionsMenu(menu, inflater);
}

When I again start Fragment A I want to options Menu DONE (which was set at Fragment B) for this I am doing like this

当我再次启动片段A时,我想要“完成选项”菜单(它被设置为片段B),我这样做

setHasOptionsMenu(false);
MenuItem item = (MenuItem) menu.findItem(R.id.done_item);
item.setVisible(false);

But this is not hiding at all, also it is giving NullPointerException when Activity if first started with Fragment A.

但这并不是隐藏的,它还提供了NullPointerException,当活动第一次以片段A开始时。

Please let me know what is the problem.

请告诉我是什么问题。

11 个解决方案

#1


58  

This is one way of doing this:

这是一种方法:

add a "group" to your menu:

在你的菜单上添加一个“组”:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <group
        android:id="@+id/main_menu_group">
         <item android:id="@+id/done_item"
              android:title="..."
              android:icon="..."
              android:showAsAction="..."/>
    </group>
</menu>

then, add a

然后,添加一个

Menu menu;

variable to your activity and set it in your override of onCreateOptionsMenu:

将变量设置为您的活动,并将其设置为onCreateOptionsMenu的覆盖:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    // inflate your menu here
}

After, add and use this function to your activity when you'd like to show/hide the menu:

之后,当您想要显示/隐藏菜单时,在您的活动中添加并使用此功能:

public void showOverflowMenu(boolean showMenu){
    if(menu == null)
        return;
    menu.setGroupVisible(R.id.main_menu_group, showMenu);
}

I am not saying this is the best/only way, but it works well for me.

我并不是说这是最好的/唯一的方式,但它对我来说很有效。

#2


85  

Try this...

试试这个…

You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.

您不需要再次在片段类中重写onCreateOptionsMenu()。可以通过重写片段类中可用的onPrepareOptionsMenu()方法来更改菜单项的可见性。

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_search).setVisible(false);
    super.onPrepareOptionsMenu(menu);
}

#3


20  

To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:

要在片段的ActionBar中显示仅需要的动作项(动作按钮),请执行以下操作:

Lets say you want the save button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu method of the Fragment where you view the items:

假设您希望save按钮只显示在您接受条目的输入的片段中,而不是在您查看项目列表的片段中,将此添加到您查看项目的片段的OnCreateOptionsMenu方法中:

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    if (menu != null) {

        menu.findItem(R.id.action_save_item).setVisible(false);
    }
}

NOTE: For this to work, you need the onCreate() method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true) like this:

注意:要实现这一点,您需要在片段中使用onCreate()方法(在我们的示例中,您希望隐藏项目按钮,项目视图片段)并添加setHasOptionsMenu(true):

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

Might not be the best option, but it works and it's simple.

也许这不是最好的选择,但它很有效而且很简单。

#4


6  

This will work for sure I guess...

我想这肯定行得通……

// Declare
Menu menu;
MenuItem menuDoneItem;

// Then in your onCreateOptionMenu() method write the following...
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        this.menu=menu;
        inflater.inflate(R.menu.secutity, menu);
            }

// In your onOptionItemSelected() method write the following...
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done_item:
                this.menuDoneItem=item;
                someOperation();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
            menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
                menuRefresh.setVisible(false); // make true to make the menu item visible.
}

//Use the above method whenever you need to make your menu item visible or invisiable

You can also refer this link for more details, it is a very useful one.

你也可以参考这个链接获得更多的细节,它是一个非常有用的链接。

#5


5  

MenuItem Import = menu.findItem(R.id.Import);
  Import.setVisible(false)

For more reference, see: http://androiddhina.blogspot.in/2015/05/android-how-to-hide-menu-item-in.html

要获得更多的引用,请参见:http://androiddhina.blogspot.in/2015/5/05/android - howto -menu-item-in.html。

#6


3  

Try this

试试这个

@Override
public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.custom_actionbar, menu);
    menu.setGroupVisible(...);
}

#7


1  

You can make a menu for each fragment, and a global variable that mark which fragment is in use now. and check the value of the variable in onCreateOptionsMenu and inflate the correct menu

您可以为每个片段创建一个菜单,以及一个全局变量,该变量标记正在使用的片段。检查onCreateOptionsMenu中的变量的值,并膨胀正确的菜单

 @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         if (fragment_it == 6) {
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.custom_actionbar, menu);
         }
     } 

#8


0  

Even though the question is old and answered. There is a simpler answer to that than the above mentioned. You don't need to use any other variables. You can create the buttons on action bar whatever the fragment you want, instead of doing the visibility stuff(show/hide).

尽管这个问题已经过时并得到了解答。有一个比上面提到的更简单的答案。你不需要使用任何其他变量。您可以在操作栏上创建任何您想要的片段的按钮,而不是做可见性的事情(显示/隐藏)。

Add the following in the fragment whatever u need the menu item.

无论您需要什么菜单项,都可以在片段中添加以下内容。

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Sample menu.xml file:

样品菜单。xml文件:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_addFlat"
        android:icon="@drawable/add"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_addFlat"/>
</menu>

Handling onclick events is as usual.

像往常一样处理onclick事件。

#9


0  

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

你好,我得到了最好的解决方案,假设您必须在create Menu方法中隐藏一个特定的项目,并在其他片段中显示该项目。我举了两个菜单项的例子一个是编辑,另一个是删除。e。g菜单xml如下所示:

sell_menu.xml

sell_menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

现在重写您的活动中的两个方法,并将字段变量mMenu设置为:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

在你的活动中做两个以下的方法&从片段中调用它们来隐藏和显示你的菜单项。这些方法:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

这是我的解决办法,我想这个解释会对你有帮助。

#10


0  

Late to the party but the answers above didn't seem to work for me.

聚会迟到了,但上面的答案似乎对我不起作用。

My first tab fragment (uses getChildFragmentManager() for inner tabs) has the menu to show a search icon and uses android.support.v7.widget.SearchView to search within the inner tab fragment but navigating to other tabs (which also have inner tabs using getChildFragmentManager()) would not remove the search icon (as not required) and therefore still accessible with no function, maybe as I am using the below (ie outer main tabs with each inner tabs)

我的第一个选项卡片段(对内部选项卡使用getChildFragmentManager()))具有显示搜索图标的菜单,并使用android.support.v7.widget。SearchView内内搜索选项卡片段但导航到其他选项卡(也有内在的标签使用getChildFragmentManager())不会删除搜索图标(不是必须的),因此仍然没有访问功能,也许因为我使用以下(即外主要标签与每一个内部标签)

getChildFragmentManager(); 

However I use the below in my fragments containing/using the getChildFragmentManager() for inner tabs.

但是,我在我的片段中使用了包含/使用getChildFragmentManager()的内部选项卡。

    //region onCreate
    @Override
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    //access setHasOptionsMenu()
    setHasOptionsMenu(true);

    }
    //endregion onCreate

and then clear the menu item inside onPrepareOptionsMenu for fragments(search icon & functions)

然后在onPrepareOptionsMenu中清除菜单项以获取片段(搜索图标和函数)

    @Override
    public void onPrepareOptionsMenu(Menu menu) {

    super.onPrepareOptionsMenu(menu);

    //clear the menu/hide the icon & disable the search access/function ...
    //this will clear the menu entirely, so rewrite/draw the menu items after if needed
    menu.clear();

    }

Works well and navigating back to the tab/inner tab with the search icon functions re displays the search icon & functions.

工作良好,导航回到标签/内部标签与搜索图标功能重新显示搜索图标和功能。

Hope this helps...

希望这有助于……

#11


0  

By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically

通过设置菜单中所有项目的可见性,将自动隐藏appbar菜单或溢出菜单

Example

例子

 private Menu menu_change_language;
 ...
 ...
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    ...
    ...
    menu_change_language = menu;
   menu_change_language.findItem(R.id.menu_change_language).setVisible(true);

    return super.onCreateOptionsMenu(menu);
}

Before going to other fragment use bellow code:

在进入其他片段之前使用下面的代码:

if(menu_change_language != null){                 
 menu_change_language.findItem(R.id.menu_change_language)
  .setVisible(false);
}

#1


58  

This is one way of doing this:

这是一种方法:

add a "group" to your menu:

在你的菜单上添加一个“组”:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <group
        android:id="@+id/main_menu_group">
         <item android:id="@+id/done_item"
              android:title="..."
              android:icon="..."
              android:showAsAction="..."/>
    </group>
</menu>

then, add a

然后,添加一个

Menu menu;

variable to your activity and set it in your override of onCreateOptionsMenu:

将变量设置为您的活动,并将其设置为onCreateOptionsMenu的覆盖:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    // inflate your menu here
}

After, add and use this function to your activity when you'd like to show/hide the menu:

之后,当您想要显示/隐藏菜单时,在您的活动中添加并使用此功能:

public void showOverflowMenu(boolean showMenu){
    if(menu == null)
        return;
    menu.setGroupVisible(R.id.main_menu_group, showMenu);
}

I am not saying this is the best/only way, but it works well for me.

我并不是说这是最好的/唯一的方式,但它对我来说很有效。

#2


85  

Try this...

试试这个…

You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.

您不需要再次在片段类中重写onCreateOptionsMenu()。可以通过重写片段类中可用的onPrepareOptionsMenu()方法来更改菜单项的可见性。

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_search).setVisible(false);
    super.onPrepareOptionsMenu(menu);
}

#3


20  

To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:

要在片段的ActionBar中显示仅需要的动作项(动作按钮),请执行以下操作:

Lets say you want the save button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu method of the Fragment where you view the items:

假设您希望save按钮只显示在您接受条目的输入的片段中,而不是在您查看项目列表的片段中,将此添加到您查看项目的片段的OnCreateOptionsMenu方法中:

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    if (menu != null) {

        menu.findItem(R.id.action_save_item).setVisible(false);
    }
}

NOTE: For this to work, you need the onCreate() method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true) like this:

注意:要实现这一点,您需要在片段中使用onCreate()方法(在我们的示例中,您希望隐藏项目按钮,项目视图片段)并添加setHasOptionsMenu(true):

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

Might not be the best option, but it works and it's simple.

也许这不是最好的选择,但它很有效而且很简单。

#4


6  

This will work for sure I guess...

我想这肯定行得通……

// Declare
Menu menu;
MenuItem menuDoneItem;

// Then in your onCreateOptionMenu() method write the following...
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        this.menu=menu;
        inflater.inflate(R.menu.secutity, menu);
            }

// In your onOptionItemSelected() method write the following...
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done_item:
                this.menuDoneItem=item;
                someOperation();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
            menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
                menuRefresh.setVisible(false); // make true to make the menu item visible.
}

//Use the above method whenever you need to make your menu item visible or invisiable

You can also refer this link for more details, it is a very useful one.

你也可以参考这个链接获得更多的细节,它是一个非常有用的链接。

#5


5  

MenuItem Import = menu.findItem(R.id.Import);
  Import.setVisible(false)

For more reference, see: http://androiddhina.blogspot.in/2015/05/android-how-to-hide-menu-item-in.html

要获得更多的引用,请参见:http://androiddhina.blogspot.in/2015/5/05/android - howto -menu-item-in.html。

#6


3  

Try this

试试这个

@Override
public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.custom_actionbar, menu);
    menu.setGroupVisible(...);
}

#7


1  

You can make a menu for each fragment, and a global variable that mark which fragment is in use now. and check the value of the variable in onCreateOptionsMenu and inflate the correct menu

您可以为每个片段创建一个菜单,以及一个全局变量,该变量标记正在使用的片段。检查onCreateOptionsMenu中的变量的值,并膨胀正确的菜单

 @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         if (fragment_it == 6) {
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.custom_actionbar, menu);
         }
     } 

#8


0  

Even though the question is old and answered. There is a simpler answer to that than the above mentioned. You don't need to use any other variables. You can create the buttons on action bar whatever the fragment you want, instead of doing the visibility stuff(show/hide).

尽管这个问题已经过时并得到了解答。有一个比上面提到的更简单的答案。你不需要使用任何其他变量。您可以在操作栏上创建任何您想要的片段的按钮,而不是做可见性的事情(显示/隐藏)。

Add the following in the fragment whatever u need the menu item.

无论您需要什么菜单项,都可以在片段中添加以下内容。

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Sample menu.xml file:

样品菜单。xml文件:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_addFlat"
        android:icon="@drawable/add"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_addFlat"/>
</menu>

Handling onclick events is as usual.

像往常一样处理onclick事件。

#9


0  

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

你好,我得到了最好的解决方案,假设您必须在create Menu方法中隐藏一个特定的项目,并在其他片段中显示该项目。我举了两个菜单项的例子一个是编辑,另一个是删除。e。g菜单xml如下所示:

sell_menu.xml

sell_menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

现在重写您的活动中的两个方法,并将字段变量mMenu设置为:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

在你的活动中做两个以下的方法&从片段中调用它们来隐藏和显示你的菜单项。这些方法:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

这是我的解决办法,我想这个解释会对你有帮助。

#10


0  

Late to the party but the answers above didn't seem to work for me.

聚会迟到了,但上面的答案似乎对我不起作用。

My first tab fragment (uses getChildFragmentManager() for inner tabs) has the menu to show a search icon and uses android.support.v7.widget.SearchView to search within the inner tab fragment but navigating to other tabs (which also have inner tabs using getChildFragmentManager()) would not remove the search icon (as not required) and therefore still accessible with no function, maybe as I am using the below (ie outer main tabs with each inner tabs)

我的第一个选项卡片段(对内部选项卡使用getChildFragmentManager()))具有显示搜索图标的菜单,并使用android.support.v7.widget。SearchView内内搜索选项卡片段但导航到其他选项卡(也有内在的标签使用getChildFragmentManager())不会删除搜索图标(不是必须的),因此仍然没有访问功能,也许因为我使用以下(即外主要标签与每一个内部标签)

getChildFragmentManager(); 

However I use the below in my fragments containing/using the getChildFragmentManager() for inner tabs.

但是,我在我的片段中使用了包含/使用getChildFragmentManager()的内部选项卡。

    //region onCreate
    @Override
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    //access setHasOptionsMenu()
    setHasOptionsMenu(true);

    }
    //endregion onCreate

and then clear the menu item inside onPrepareOptionsMenu for fragments(search icon & functions)

然后在onPrepareOptionsMenu中清除菜单项以获取片段(搜索图标和函数)

    @Override
    public void onPrepareOptionsMenu(Menu menu) {

    super.onPrepareOptionsMenu(menu);

    //clear the menu/hide the icon & disable the search access/function ...
    //this will clear the menu entirely, so rewrite/draw the menu items after if needed
    menu.clear();

    }

Works well and navigating back to the tab/inner tab with the search icon functions re displays the search icon & functions.

工作良好,导航回到标签/内部标签与搜索图标功能重新显示搜索图标和功能。

Hope this helps...

希望这有助于……

#11


0  

By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically

通过设置菜单中所有项目的可见性,将自动隐藏appbar菜单或溢出菜单

Example

例子

 private Menu menu_change_language;
 ...
 ...
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    ...
    ...
    menu_change_language = menu;
   menu_change_language.findItem(R.id.menu_change_language).setVisible(true);

    return super.onCreateOptionsMenu(menu);
}

Before going to other fragment use bellow code:

在进入其他片段之前使用下面的代码:

if(menu_change_language != null){                 
 menu_change_language.findItem(R.id.menu_change_language)
  .setVisible(false);
}