How to get an MenuItem by id

走远了吗. 提交于 2019-11-30 01:42:04

问题


I have my menuItem on my res/menu/student_marks.xml file:

<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>

Now i need for this item to set a title.in a specific part of my app.

I can work with a specific item in this method:

onOptionsItemSelected(MenuItem item)

the problem is that i need the item 'action_selected_year' without of this method but in another part of my program.
I don't have idea how to get it.


回答1:


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;
    }

example: change icon on first menuItem (optionsMenu should be != null)

optionsMenu.getItem(0).setIcon(getResources()
    .getDrawable(R.drawable.ic_action_green));



回答2:


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;
}

And to get a menu item:

MenuItem item = optionsMenu.findItem(R.id. action_selected_year);


来源:https://stackoverflow.com/questions/26877059/how-to-get-an-menuitem-by-id

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