onCreateOptionsMenu nunca se llama


Estoy teniendo algunos problemas para conseguir un menú de opciones de trabajo en Android. Construyo aplicaciones antes, y todas funcionaban bien, pero ahora el menú simplemente no aparece.

El código:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.activity_video, menu);
    return true;
}

Ni siquiera se llama al método completo (se comprueba estableciendo un punto de interrupción). La actividad es súper simple, solo tiene un VideoView en ella, con un conjunto OnTouchListener.

Estoy usando Android 4.0.4 en un Samsung Galaxy 10.1, nivel de API 15, minSdk 15. Me estoy perdiendo algo?

Author: Bart Friederichs, 2012-11-07

9 answers

Si el teléfono en el que prueba tiene un botón de menú onCreateOptionsMenu no se llamará al iniciar con el tema:

android:theme="@android:style/Theme.Black.NoTitleBar"

Pero cuando haga clic en el botón de menú, se llamará a onCreateOptionsMenu. No se que pasa en teléfonos sin botones de hardware...

 24
Author: Warpzit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-07 10:05:43

En las últimas versiones de Android cuando se utiliza la biblioteca compat para la barra de herramientas, es muy común que esto suceda, con el fin de obtener los elementos de menú para mostrar en la barra de herramientas debe hacer lo siguiente:

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
 54
Author: Martin Cazares,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-29 18:37:45

Llama a la función setHasOptionsMenu desde onCreate primero. El onCreateOptionsMenu será llamado automáticamente.

 38
Author: noahutz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-18 03:44:49

En el método: Fragment#onCreateView(...) usted debe poner:

setHasOptionsMenu(true);

Entonces se llamará a tu método.

 16
Author: Sterling Diaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 03:04:07

Estaba teniendo el mismo problema (el menú no aparece, onCreateOptionsMenu no se llama).

Si estás llamando a esto dentro de un fragmento, necesitas anular public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) no public boolean onCreateOptionsMenu(Menu menu). Fragments no use este último, por lo que ni siquiera lo llamarán.

Menú de actividades

Menú de fragmentos

 5
Author: Daynil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-14 14:50:56

Tuve el mismo problema. Mi problema fue resuelto por herencia de una clase de actividad diferente.

Así que había estado haciendo:

La clase pública WelcomeActivity extiende la actividad

Pero cambió esto a:

La clase pública WelcomeActivity extiende AppCompatActivity

De esta manera estaba diciendo que digamos que se puede agregar una barra de acción a su actividad.

 2
Author: P Wilson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-15 11:29:22

Tal vez también haya anulado el método onKeyDown y lo haya hecho siempre devolver verdadero. Devolver true significa que se evitará que KeyEvent se propague más. Véase el código siguiente:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
        /*
          handling event
         */
        return true; //onCreateOptionsMenu won't be invoked.
}
 1
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-16 08:17:32

Tuve un problema similar, pero una solución diferente que estoy compartiendo con la comunidad (ya que me tomó una hora entender lo que estaba sucediendo):

    abstract class BaseActivity : AppCompatActivity{
      override fun onCreate(savedInstanceState: Bundle?) {
      setSupportActionBar(my_toolbar)
      }
    }
    class MyActivity : BaseActivity{
        // TODO : some good stuff
    }

Donde my_toolbar es un objeto creado en mi archivo xml a través de DataBinding.

El problema se ve igual, no aparece ninguna barra de herramientas, no hay llamada a onCreateOptionsMenu.

Mi solución fue promover este código a la clase hija y no a ese básico, ya que my_toolbar solo se inicializa a medida que se construye la clase hija.

 0
Author: AnthonyCFE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 22:17:02

Prueba esto Funciona para mí: - - -

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.home_page_menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.menu_delete:
        Toast.makeText(this, "You pressed the Delete!",
                 Toast.LENGTH_LONG).show();
        break;


      case R.id.menu_setting:
     Intent intent=new Intent(HomePage.this,Setting.class);
     startActivity(intent);
     finish();
     Toast.makeText(this, "You pressed the Setting!",
     Toast.LENGTH_LONG).show(); break;


    }

    return super.onOptionsItemSelected(item);
}
 -2
Author: Deepanker Chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-07 09:54:32