Hide MenuItem in some Fragments

后端 未结 13 2104
南方客
南方客 2020-12-07 20:00

I using menu drawer which has more Fragments. In some Fragments I have menu item REFRESH but in some fragments I want hide this menu item (I don\'t

相关标签:
13条回答
  • 2020-12-07 20:26

    please try this

    @Override 
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
    }
    

    and put this on your fragmen's onCreate()

    setHasOptionsMenu(true);
    
    0 讨论(0)
  • 2020-12-07 20:29

    Or solve it in the same Fragment which created the menu, if you host the Actionbar on Activity level. This way you don't have to add it on every other Fragment where you don't want to show it:

    public override void OnDestroy()
    {
        base.OnDestroy();
        HasOptionsMenu = false;
    }
    
    0 讨论(0)
  • 2020-12-07 20:29

    Add these functions to your Fragment

      @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setHasOptionsMenu(true);
            }
            @Override
            public void onPrepareOptionsMenu(Menu menu) {
                MenuItem item=menu.findItem(R.id.delete);
                item.setVisible(false);
            }
    
    0 讨论(0)
  • 2020-12-07 20:31

    in Kotlin

    override fun onPrepareOptionsMenu(menu: Menu) {
        val item: MenuItem = menu.findItem(R.id.action_search)
        item.isVisible = false
    }
    

    in onCreate() of your fragment setHasOptionsMenu(true)

    0 讨论(0)
  • 2020-12-07 20:31

    Firstly in your Activity that has the toolbar, create a method that sets up the overflow menu for you:

    public void setUpOptionMenu(Toolbar toolbar){
        this.setSupportActionBar(toolbar);
    }
    

    In your fragments onCreateView() method, get the reference of your current activity and call your activities setUpOptionMenu() method:

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        ...
        ...
        public void ((YourActivityName)this.getActivity()).setUpOptionMenu(null);
        ...
        ...
    }
    

    Cheers!!!

    0 讨论(0)
  • 2020-12-07 20:33

    In the Fragment where you don't want to show any menu options, you need setHasOptionsMenu(false); in the onCreate(), like this:

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

    However, the menu that is being shown that you would like to hide (REFRESH), belongs to MainActivity. That is why it is always shown. Since you want to control the menu at the Fragment level (and not show an Activity options menu), my suggestion is to delete the menu code from the Activity and implement it in your Fragment.

    Activitys and Fragments can each have their own separate menus. See this link.

    0 讨论(0)
提交回复
热议问题