how to access item from another item in toolbar? For example, if I click on item1, then I need to change item2

@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.item_left: return true; case R.id.item_button: // если я нажимаю на этот item, то title'ы item_left и item_right должно поменяться местами return true; case R.id.item_right: return true; default: return super.onOptionsItemSelected(item); } 
  • Can you add the code that you already have? With him it would be easier to understand what kind of decision to advise. - Komdosh
  • Everything added ... - Almaz Miftakhov
  • I tried this: MenuItem ileft = (MenuItem) findViewById (R.Id.item_left); but no way - Almaz Miftakhov

1 answer 1

You can save a link to the menu in onCreateOptionsMenu , and then through it access the elements.

 public class MainActivity extends Activity { private Menu menu; //... @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //... this.menu = menu; return true; } private void changeLeftItem() { MenuItem leftItem = menu.findItem(R.id.item_left); leftItem.setTitle("Другое название"); } } 
  • Is it possible to implement this in onOptionsItemSelected? - Almaz Miftakhov
  • In onOptionsItemSelected specific item passed from it; it will not work to pull out the Menu , so the link is pulled from onCreateOptionsMenu or onPrepareOptionsMenu . But no one forbids you to override onOptionsItemSelected and onCreateOptionsMenu in the same class. - Komdosh
  • I did not understand how to pull out the menu: this.menu = menu; - Almaz Miftakhov
  • As it is written in the answer, you override the onCreateOptionsMenu method and inside this.menu = menu; - Komdosh
  • I realized. Thank! - Almaz Miftakhov