How can I set the visibility of an ActionBar item

2020-02-28 17:48发布

I'm looking for a way to set the visibility of a MenuItem inflated in my MainActivity depending on which Fragment I am on.

For information: I'm using actionBarSherlock, zxing, and some google services.

The application was built with a Navigation drawer(With abs), also I manipulate the FragmentStack in such way I everytime I switch to another Fragment when I press the touch back I come back in my Main Fragment.

Here my menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   <item android:id="@+id/button_generator" android:title="GENERER" android:icon="@drawable/ic_drawer"></item>
</menu>

Here is where I inflate the menu:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    Log.d(TAG, "================= onCreateOptionsMenu ================= fragSt: " + fragmentStatus);
    this.getSherlock().getMenuInflater().inflate(R.menu.main, menu);

    mGenQrFromContacts = menu.findItem(R.id.button_generator);


    return true;
}

I've tried the solution purposed here, but ain't work in my case.

3条回答
smile是对你的礼貌
2楼-- · 2020-02-28 18:31

You should try this in your Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // ...  
    // call the method setHasOptionsMenu, to have access to the menu from your fragment
    setHasOptionsMenu(true);

    //...
}

// the create options menu with a MenuInflater to have the menu from your fragment
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.findItem(R.id.button_generator).setVisible(true);
    super.onCreateOptionsMenu(menu, inflater);
}  

And this, in your Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.my_layout, menu);
    menu.findItem(R.id.button_generator).setVisible(false);
    return true;
}

Hope this helps.

查看更多
再贱就再见
3楼-- · 2020-02-28 18:35

when you want to change fragment you will need to set a flag indicating what menu you want inflated then all you have to do is call invalidateOptionsMenu() in your activity to call onCreateOptonsMenu again and using your flag you set you inflate a different menu

查看更多
孤傲高冷的网名
4楼-- · 2020-02-28 18:41

I found a trick, you might wanna try this.

public void displayMenu(boolean show) {
        setHasOptionsMenu(show);
        getActivity().invalidateOptionsMenu();
}
查看更多
登录 后发表回答