Link

Action Bar

En este ejemplo vamos a añadir un menú al Action Bar de una actividad (barra superior)

1. Creamos el directorio menu:

Android

2. Creamos un fichero menu.xml en el directorio recién creado:

Android

3. Crearemos el diseño:

Android

Recuerda algunos atributos importantes para el comportamiento de algunos elementos de la interface:

Android

4. Desde la actividad inflamos el menú implementado el siguiente método:

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        // Indicamos nuestro recurso menú anteriormente creado
        inflater.inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

5. Y por último, comprobamos cuando el usuario ha pulsado alguna opción:

    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item1:
                Toast.makeText(this, "Se ha pulsado el item1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item2:
                Toast.makeText(this, "Se ha pulsado el item2", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item3:
                Toast.makeText(this, "Se ha pulsado el item3", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item4:
                Toast.makeText(this, "Se ha pulsado el item4", Toast.LENGTH_SHORT).show();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

Visita los siguientes enlaces para ver un ejemplo en funcionamiento: