如何通过id获取MenuItem

Gio*_*Far 12 android menuitem

我的res/menu/student_marks.xml文件中有menuItem:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".StudentMarks" >
    <item android:id="@+id/action_selected_year"
        android:title="@string/action_selected_year"
        android:showAsAction="withText|ifRoom"
        style="@style/AppTheme" />
</menu>
Run Code Online (Sandbox Code Playgroud)

现在我需要这个项目来设置我的应用程序的特定部分的标题.

我可以使用此方法中的特定项目:

onOptionsItemSelected(MenuItem item)
Run Code Online (Sandbox Code Playgroud)

问题是我需要项目'action_selected_year'而不使用此方法,但在我的程序的另一部分.
我不知道如何得到它.

小智 21

Menu optionsMenu;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.main, menu);
   //  store the menu to var when creating options menu
   optionsMenu = menu;
}
Run Code Online (Sandbox Code Playgroud)

并获得一个菜单项:

MenuItem item = optionsMenu.findItem(R.id. action_selected_year);
Run Code Online (Sandbox Code Playgroud)

  • 您还可以直接从工具栏检索菜单(如果它是布局中的工具栏):确保您的工具栏在布局中有一个 ID,并通过 KTX 或 ViewBinding 检索它。假设我们正在使用 ViewBinding,它看起来像:“viewBinding.my_toolbar_id.menu.findItem(id_of_my_menu_item)” 不需要存储任何变量。 (2认同)

Mic*_* D. 6

Menu optionsMenu;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.main, menu);
       //  store the menu to var when creating options menu
       optionsMenu = menu;
    }
Run Code Online (Sandbox Code Playgroud)

示例:更改第一个menuItem上的图标(optionsMenu应为!= null)

optionsMenu.getItem(0).setIcon(getResources()
    .getDrawable(R.drawable.ic_action_green));
Run Code Online (Sandbox Code Playgroud)

  • 这不会通过ID获取菜单项.这只是返回第一个菜单项. (9认同)
  • 你可以调用findItem()并传递你正在寻找的id,而不是调用getItem(0). (7认同)