Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

It might be easier to have the second button already on the menu but visibility set to GONE, and then make it visible when you need.

MenuItem = menu.findItem(R.id.menuItem);

MenuItem.setVisible(false);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top