Question

How can I show the value in my EditText into an optionsMenu on Button click?

E.g. If I enter abc in EditText and then I press a Button (add Button), then I should be getting an optionsMenu with abc added into it.

Was it helpful?

Solution

Firstly, create a global Menu variable (outside of any method, but inside the class):

private Menu menu;

Then, in onCreateOptionsMenu(Menu menu), assign that menu to be your menu, like so:

@Override 
public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);
    this.menu = menu; // here

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main, menu); // inflate your menu resource
    return true;
}

Then, you can use the .add(int groupId, int itemId, int order, CharSequence title) method to add the EditText text to your options menu, like so:

// in your Button click listener:
EditText et = (EditText)findViewById(R.id.et);
if (et.length() > 0) {
    int NEW_MENU_ID = 2352; // arbitrary number
    menu.add(0, NEW_MENU_ID, 0, et.getText().toString()); 
}

And then it's done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top