I menù sono molto importanti in una applicazione Android perché offrono un modo semplice per accedere alle funzioni e alla configurazione di una applicazione. I menù sono legati all’attività (Activity) corrente. Il menù appare quando viene premuto il pulsante “menù” sul telefono.
Per creare un menù personalizzato per la nostra applicazione, seguiremo questi seguenti passi:
- Definire il menù e i suoi oggetti
- Gestire l’evento del pulsante menù sul nostro telefono
- Gestire l’oggetto selezionato
DEFINIRE IL MENU
Define the menu is a very simple step. We just create a xml file in /res/menu/ directory of the our project like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/setting"
android:icon="@drawable/ic_setting"
android:title="@string/setting" />
<item android:id="@+id/quit"
android:icon="@drawable/ic_quit"
android:title="@string/quit" />
</menu>
The xml above is composed by two main parts (or two tags):
- The menu tag
- The item tag
The menu tag is the root tag of the file. We just past and copy into our xml.
The item tag describe our menu button. It’s formed by three property:
- android:id. It is a unique id that we want assign to the button and we will use to refer it into the code.
- android:icon. It is optional and it is add an icon to the button. The icon must be placed into /res/drawable/ directory. For more info about menu icons go here.
- android:title. The string that is showed into the menu button.
HANDLING THE EVENT MENU BUTTON
When we press the menu button on the device, the onCreateOptionsMenu method is triggered.
We just add this method on the Activity:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.setting_menu, menu);
return true;
}
The getMenuInflater() method returns a MenuInflater for the Activity.
With this object, you can call inflate(), which put a menu resource into a Menu object.
In this example, the menu resource defined by setting_menu.xml is putted into the Menu that was passed into onCreateOptionsMenu().
MANAGE A SELECTED ITEM
When the user select an item from the menu, the method onOptionsItemSelected() is called from the Activity. This method passes the MenuItem that the user selected. We can identify the menu item just calling getItem() method of the MenuItem object. This method return the unique id defined by android:id property into the xml file. We use this id to perform appropriate action.
Below there is a small example:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.setting:
doSomething();
return true;
case R.id.quit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
That’s all.
We have done a simple menu.