如何通过id获取MenuItem [英] How to get an MenuItem by id

查看:246
本文介绍了如何通过id获取MenuItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

问题是我需要项目'action_selected_year',而没有这种方法,但是在程序的另一部分.
我不知道如何获得它.

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.

推荐答案

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

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

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

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

这篇关于如何通过id获取MenuItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆