Search code examples
androidrefreshoptionmenu

Change option menu's items on item selection


I'm trying to change the option menu after an item on the menu is selected. This is what I tried:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    if(refresh) {

        menu.clear();
        menu.add(0, Menu.FIRST, 0, "Changed item");

    }

    return super.onPrepareOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if(item.getItemId() == R.id.refresh)
    {
        refresh = true;
        closeOptionsMenu();
        invalidateOptionsMenu();
        openOptionsMenu();
    }
    return super.onOptionsItemSelected(item);
}

But I get:

W/InputManagerService(192): Window already focused, ignoring focus gain of:     com.android.internal.view.IInputMethodClient$Stub$Proxy@4147c778

and the code is not working.. Any idea?


Solution

  • the menu will close and not reopen, only if i reclick on the menu button i see the new value

    I don't know of anyway to keep the options menu open after an item has been selected, however you can reopen it automatically with a Handler and Runnable.

    Create a couple new field variables:

    private Handler handler = new Handler();
    private Runnable reopenMenu = new Runnable() {
        @Override
        public void run() {
            openOptionsMenu();
        }
    };
    

    And inside onOptionsItemSelected() use:

    if(item.getItemId() == R.id.refresh)
    {
        refresh = true;
        invalidateOptionsMenu(); // This is only necessary for changing an ActionBar
        handler.postDelayed(reopenMenu, 100);
    }
    

    (Notice I removed the calls to close and open the menu.)
    Lastly you should set refresh = false; in onPrepareOptionsMenu() since you only need to make the change once.