隐藏/显示不同片段的操作栏选项菜单项 [英] Hide/Show Action Bar Option Menu Item for different fragments

查看:30
本文介绍了隐藏/显示不同片段的操作栏选项菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Sherlock 片段活动,其中有 3 个片段.

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

片段A、片段B、片段C是三个片段.我只想在片段 B 中显示完成的选项菜单.

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

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

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

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

当我再次启动 Fragment A 时,我想为此选择 Menu DONE(在 Fragment B 中设置),我正在这样做

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

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

但这根本没有隐藏,如果 Activity 首次从 Fragment A 开始,它也会给出 NullPointerException.

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

请告诉我是什么问题.

推荐答案

这是一种方法:

在您的菜单中添加一个组":

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>

然后,添加一个

Menu menu;

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

variable to your activity and set it in your override of 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.

这篇关于隐藏/显示不同片段的操作栏选项菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆