Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android getMenuInflater() in a 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 raises the following error:

Cannot resolve method 'getMenuInflater()'

I tried :

MenuInflater inflater = getActivity().getMenuInflater();

but then Android Studio highlights @Override in red and states:

Method does not override method from its superclass

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

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

but then the following error is thrown :

error: incompatible types: ForecastFragment cannot be converted to Context

error: method does not override or implement a method from a supertype

What do I do?

like image 604
Flame of udun Avatar asked Jun 15 '15 13:06

Flame of udun


3 Answers

The signature of your onCreateOptionsMenu doesn't look right. Take a look at the docs here

Take a look 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);
}
like image 54
Zain Avatar answered Nov 14 '22 20:11

Zain


In your fragment class add:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.[IDMENU], menu) ;
}

Where [IDMENU] is the XML name of your menu.

Next you need to add inside onCreate or onCreateView method this:

setHasOptionsMenu(true);
like image 5
Marco Concas Avatar answered Nov 14 '22 21:11

Marco Concas


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 ID of the item in the menu forcastfragment.xml. Also add setHasOptionsMenu(true); in your OnCreateView() so that the fragment will call the method.

As a side, it's standard practice to include the word 'menu' in your menu file names such as 'forecastfragment_menu.xml'. It avoids confusion.

like image 2
McGuile Avatar answered Nov 14 '22 20:11

McGuile