Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an MenuItem by id

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.

like image 914
Giovanni Far Avatar asked Nov 12 '14 00:11

Giovanni Far


People also ask

Where do I find MenuItem ID?

You can call findItem() and pass the id you're looking for, instead of calling getItem(0).

How do I get MenuItem?

you can access the MenuItem with the id menuItemPinQuote like this in your Android/Java code: public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { menuInflater.

What is menu item in android?

android.view.MenuItem. Interface for direct access to a previously created menu item. An Item is returned by calling one of the Menu. add(int) methods. For a feature set of specific menu types, see Menu .


1 Answers

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);
like image 127
Esteban Atenor Avatar answered Oct 26 '22 00:10

Esteban Atenor