Android:命名菜单文件
我是 Android SDK(不是 java)的新手,我对选项菜单有一两个问题。我查找了一些教程,包括developer.android 教程。我的问题是文件的命名。当我的 res/menu 文件夹中菜单 xml 文档的标题为 menu.xml 时,菜单工作正常。如果我尝试调用 mainMenu.xml 我会得到一个 mainMenu 无法解析或不是字段 错误。 这是我的主要活动中的代码,
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainMenu, menu);
return true;
}
上面代码中的 R.menu.mainMenu 中的“mainMenu”用红色下划线表示(错误) 所以我的问题是我可以将菜单文件命名为任何我想要的名称吗?这种方式似乎限制了我每个项目只有一个选项菜单,这是不正确的(除非我错过了一些东西:)
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 : )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您绝对可以有多个选项菜单:不过可能有小写限制。使用下划线就应该准备好了?
编辑:是的,当您尝试构建时会出现此错误消息:
因此存在小写限制。从来不知道这一点。
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:
So there is a lower case restriction. Never knew that.
问题在于您为 XML 文件选择的名称。以下是名为
someName
的文件的示例输出::必须仅包含 [a-z0-9_。]如您所见,您的文件允许包含任何小写字符、数字、下划线或句点。由于您将文件命名为
mainMenu
,因此大写的M
会导致问题。一般来说,camel-case对于Android资源来说是不可行的,你应该使用snake-case。
另外,关于您的
onCreateOptionsMenu
方法的一点说明:Activity 的上下文已经为您提供了一个菜单充气器,您不必创建一个:
The problem is the name you have chosen for your XML-file. Here is an example-output for a file named
someName
: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-caseM
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: