A
A
artshelom2017-07-22 21:41:46
Android
artshelom, 2017-07-22 21:41:46

How to add item item to menu in android?

I am new to this I have 2 questions:
1. I have a standard code

<item android:id="@+id/nav_favorites"
        android:title="@string/favorites">
        <menu android:id="@+id/nav_favorites_main">
            <item
                android:id="@+id/nav_share"
                android:title="Share" />
        </menu>
    </item>

I need to add one more item item there () through Java itself.
2. As I understand it, almost any element added to xml is added via fragment and event processing takes place in the corresponding fragment of the Java code (if I misunderstood, correct me). Is it possible to use the same fragment by changing the text and id, to work out different button clicks??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
subway, 2017-07-23
@artshelom

one.

Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.add(Menu.NONE, nav_share, Menu.NONE, "Share");
    super.onCreateOptionsMenu(menu, inflater);
}

Parameters to be passed to the add(int groupId, int itemId, int order, CharSequence title) method
2. ID cannot be changed dynamically, you can delete the menu item and add a new one with a new title and ID. And just the text can be updated programmatically
public class MyFragment extends Fragment {
  private Menu menu;
  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     this.menu = menu;
     super.onCreateOptionsMenu(menu, inflater);
  }

  private void updateTitle () {
     MenuItem shareItem = menu.findItem(R.id.share);
     shareItem.setTitle("Поделиться");
  }
}

You can also try onPrepareOptionsMenu() which is called every time the menu is opened.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question