Options Menu Example

This example shows how to attach a menu to a device's menu button or icon.

A screenshot of the application.

We import the classes and modules needed by our application. The most relevant classes to this example are Menu and MenuItem.

from java.util import ArrayList
from android.app import Activity
import android.os
from android.view import Menu, MenuItem
from android.widget import TextView

The OptionsMenuActivity class is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it.

class OptionsMenuActivity(Activity):

We define a field to hold the items that have been placed in the menu. This is unnecessary in this example because we can directly create a list of items and assign it to an attribute, but this shows the syntax that fields use.

    __fields__ = {"items": ArrayList(MenuItem)}

The initialisation method simply calls the corresponding method in the base class and creates a list of items using a custom class, assigning it to the attribute defined by the above field.

    def __init__(self):
    
        Activity.__init__(self)
        self.items = MenuItemList()

The onCreate method is called when the activity is created. We call the corresponding method of the base class to set up the application before creating the user interface, displaying a message in the activity.

    @args(void, [android.os.Bundle])
    def onCreate(self, bundle):
    
        Activity.onCreate(self, bundle)
        
        self.view = TextView(self)
        self.view.setText("Select an item from the menu.")
        
        self.setContentView(self.view)

We reimplement the onCreateOptionsMenu method to add items to the menu. This is called when the menu needs to be populated. We return True to indicate that we populated the menu.

    @args(bool, [Menu])
    def onCreateOptionsMenu(self, menu):
    
        self.items.add(menu.add("Hello"))
        self.items.add(menu.add("World"))
        return True

We reimplement the onOptionsItemSelected method to handle user selections, updating the TextView in the user interface to show the item's title and return True to indicate that we processed the input.

    @args(bool, [MenuItem])
    def onOptionsItemSelected(self, item):
    
        self.view.setText(item.getTitle())
        return True

The MenuItemList class is our way of creating new lists of menu items since Serpentine does not have a way of writing templates. Instead, we define a new class based on a container class, ArrayList, and use the __item_types__ attribute to define the item type that instances of this class will hold. This attribute is only used at compile time.

class MenuItemList(ArrayList):

    __item_types__ = [MenuItem]
    
    def __init__(self):
        ArrayList.__init__(self)

Files