android getMenuInflater() in a fragment subclass - cannot resolve method

一笑奈何 提交于 2019-12-03 05:36:48

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);
}
  • According to API not overriding a super method.
  • You are not calling the correct method inflate.

You must use it in this way:

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

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!