Android getMenuInflater () in fragment subclass - cannot resolve method

I am trying to inflate a menu in a class that inherits the Fragment class. Here is my OnCreateOptionsMenu() method -

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

This causes the following error:

Unable to resolve getMenuInflater () 'method

I tried:

 MenuInflater inflater = getActivity().getMenuInflater(); 

but then Android Studio highlights @Override red and states:

The method does not cancel the method from its superclass

I also tried to create the getMenuInflater method in the same class and return it new MenuInflater(this)

 public MenuInflater getMenuInflater() { return new MenuInflater(this); } 

but then the following error is thrown:

error: incompatible types: ForecastFragment could not be converted to Context

error: the method does not override or does not implement the method from the super type

What should I do?

+7
java android android-fragments android-menu
source share
3 answers

The signature of your onCreateOptionsMenu does not look like this. Take a look at the docs here

Check out this code

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);//Make sure you have this line of code. } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // TODO Add your menu entries here super.onCreateOptionsMenu(menu, inflater); } 
+7
source share
  • According to the API, not overriding a super .
  • You are not calling the correct inflate method.

You should use it this way:

 @Override public boolean OnCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment, menu); return true; } 
+1
source share

Use this code:

 @Override public boolean OnCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment, menu) ; final MenuItem item = menu.findItem(R.id.forecastID); } 

where forecastID is the identifier of the item in the forcastfragment.xml menu. Also add setHasOptionsMenu(true); into your OnCreateView() so that the fragment calls the method.

As a side, standard practice includes the word โ€œmenuโ€ in the names of menu files, such as โ€œforecast fragment_menu.xmlโ€. This avoids confusion.

0
source share

All Articles