javaandroidmenuandroid-inflate

How to change deprecated onPrepareOptionsMenu


I tried to change code for deprecated menu methods such as setHasOptionsMenu, onPrepareOptionsMenu... used in fragment. I found maybe similar task link, but I don't know how to change.

Here is current code:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true); //<--deprecated
}

@Override
public void onPrepareOptionsMenu(Menu menu) {  //<--deprecated
    MenuItem item=menu.findItem(R.id.action_refresh);
    if(item != null)
        item.setVisible(false);
}

Thanks.

EDIT

I'am not sure if I understand changes of Android SDK. Do I have to remove onCreateOptionsMenu from Activity and put addMenuProvider to every fragment with onPrepareMenu? I have only one menu.xml and I want to hide some item in some fragment.


Solution

  • So, I am not sure, if it is ok, but this modification working. In activity I left menu methods:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    

    In a fragments I put these:

    requireActivity().addMenuProvider(new MenuProvider() {
            @Override
            public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
            }
    
            @Override
            public void onPrepareMenu(@NonNull Menu menu) {
                MenuItem item=menu.findItem(R.id.action_delete_tags);
                if(item != null)
                    item.setVisible(false);
            }
    
            @Override
            public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
                //...
    
                return false;
            }
        }, getViewLifecycleOwner(), Lifecycle.State.RESUMED);
    

    It seems to work. It was necessary drop inflate from onCreateMenu and add onPrepareMenu.