How to get MenuItem by ID

I have a menu item in res / menu / student_marks.xml:

<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 this element to set title.in in a specific part of my application.

I can work with a specific element in this method:

 onOptionsItemSelected(MenuItem item) 

The problem is that I need the "action_selected_year" element without this method, but in a different part of my program.
I have no idea how to get it.

+5
source share
2 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; } 

example: change icon in the first menuItem element (optionsMenu must be! = null)

 optionsMenu.getItem(0).setIcon(getResources() .getDrawable(R.drawable.ic_action_green)); 
+6
source
 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 the menu item:

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

Source: https://habr.com/ru/post/1206679/


All Articles