Question

I am new to Android SDK (not java) and I had a question or two about options menus. I look around for several tutorials, including the developer.android one. My problem is the naming of files. The menu works fine when in my res/menu folder the menu xml document is titled menu.xml. If I try to call in mainMenu.xml I get a mainMenu cannot be resolved or is not a field error. Here is the code in my main activity,

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainMenu, menu);
    return true;
}

The "mainMenu" in R.menu.mainMenu in the above code is underlined in red (error) So my question is can I name my menu file anything I want? This way seems to restrict me to one options menu per project which cannot be correct (unless I am missing something : )

Was it helpful?

Solution

You can definitely have multiple options menus: there may be a lower case restriction though. Use underscores and you should be all set?

EDIT: yep, this error message occurs when you try and build:

[2011-05-20 12:09:40 - BlAH BLAH BLAH] res\menu\newMenu.xml: Invalid file name: must contain only [a-z0-9_.]

So there is a lower case restriction. Never knew that.

OTHER TIPS

The problem is the name you have chosen for your XML-file. Here is an example-output for a file named someName:

res/menu/someName.xml: Invalid file

name: must contain only [a-z0-9_.]

As you can see, your file is allowed to contain any lower-case characters, numbers, an underscore or a period. Since you named your file mainMenu, the upper-case M is causing problems.

In general, camel-case is not feasible for Android resources, you should use snake-case.

Also, a little note on your onCreateOptionsMenu-method: The Context of the Activity already provides you with a Menu inflater, you don't have to create one:

@Override
public boolean onCreateOptionsMenu(Menu menu){
  this.getMenuInflater().inflate(R.menu.main_menu, menu);
  return super.onCreateOptionsMenu(menu);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top