什么是 onCreateOptionsMenu(菜单菜单)

What is onCreateOptionsMenu(Menu menu)

方法onCreateOptionsMenu(Menu menu)中的Menu和menu这两个参数是什么,如何使用这个方法。 我还有一个问题,为什么在

中使用 this 参数
Intent intent = new Intent(this, DisplayMessageActivity.class);

Menu就是参数菜单的类型。例如,您可以为名为 string、dog 等的变量设置 String 类型。在本例中,为名为 menu 的参数设置了 Menu 类型。

您使用 onCreateOptionsMenu() 为 activity 指定选项菜单。 在此方法中,您可以将菜单资源(在 XML 中定义)扩展到回调中提供的菜单中。

例如:

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

有关详细信息,请访问此 link

至于this

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called.

例如:

public void sendMessage() {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
}

构造函数有两个参数和一个上下文作为第一个参数。 this 表示环境数据并提供有关应用程序环境的全局信息。

有关您提供的意图示例的更多信息,请查看 this

首先,在 onCreateOptionsMenu(Menu menu) 函数中,您只传递了一个参数,而不是两个。您正在那里传递菜单 class 的对象。我们使用这个函数来覆盖默认函数来自定义我们自己的菜单,比如在菜单中添加按钮和文本、图像等。

For more reference

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

实施此方法的目的是用您在 R.menu.game_menu 布局文件中定义的项目填充传递的 menu

#Java

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

#科特林

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.game_menu, menu)
    return true
}

用项目扩充菜单后,您可能希望在选择项目时添加一些操作:

Java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_item:
            // Action goes here
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

科特林

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.menu_item -> {
            // Action goes here
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

什么时候调用onCreateOptionsMenu

onCreateOptionsMenu() 在需要创建选项菜单时由 Android 运行时调用。

Android Developer Guide: Menus

If you've developed your application for Android 2.3.x and lower, the system calls onCreateOptionsMenu() to create the options menu when the user opens the menu for the first time. If you've developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the app bar.

如何建立选项菜单?

请参考其他答案

为什么 onCreateOptionsMenu return Boolean

Activity.html#onCreateOptionsMenu

You must return true for the menu to be displayed; if you return false it will not be shown.

为什么onOptionsItemSelectedreturnBoolean

When you successfully handle a menu item, return true. If you don't handle the menu item, you should call the superclass implementation of onOptionsItemSelected() (the default implementation returns false).