onPrepareOptionsMenu not getting called in Fragments

后端 未结 4 1261
花落未央
花落未央 2021-01-07 17:34
    @Override
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
        Log.d(\"Does\", \"get called\");
        inflater.inflate(R.menu.menuItem         


        
相关标签:
4条回答
  • 2021-01-07 18:21

    Probably too late, but I had same problem and the solution was really simple. Just call getActivity().invalidateOptionsMenu() from your fragment. This will call onPrepareOptionsMenu and here you can control the visibility of your items like this: menu.findItem(R.id.youritem).setVisible(true/false); Hope that helps!

    0 讨论(0)
  • 2021-01-07 18:25

    This works for me.

    public class ContentFragment extends android.support.v4.app.Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.content_frame,container,false);
            setHasOptionsMenu(true);
            return v;
        }
    
        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.note_menu,menu);
            super.onCreateOptionsMenu(menu, inflater);
        }
    }
    
    0 讨论(0)
  • 2021-01-07 18:30

    On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

    http://developer.android.com/guide/topics/ui/menus.html

    To change particular item use: menu.findItem(R.id.your_item_id)

    0 讨论(0)
  • 2021-01-07 18:33

    You need to do two things. Step 1: In Fragment OnCreateView add setHasOptionsMenu(true);

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment_user_settings, container, false);
    }
    

    Step 2: you need to add getActivity().invalidateOptionsMenu(); in your fragment in OnViewCreated. Or in mainActivity when you change the Fragment.

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